import React, { Component, Fragment } from "react";
import { BrowserRouter as Router, Route, Link, Redirect, Switch } from "react-router-dom";
import {
    Layout, Menu, Icon, Table, Divider, Button, Modal, Form, Input,
    TimePicker, Popconfirm, message, Alert, DatePicker, Tree, Steps,
    Select, Tabs, List, Card, Collapse, Dropdown, Drawer, Skeleton,
    Transfer, Tag, Col, Row, Avatar, AutoComplete, Empty, notification,
    Progress, Spin, Rate, Upload
} from "antd";
import {
    allTeamBySchoolApi, deleteTeamApi, addTeamApi, updateTeamApi, addTeammateApi, getAllClassByMemberNameApi, 
    getTeammateByTeamIdApi, deleteTeammateApi, setChargeManApi, getallAvailablePeopleByTeamIdApi,
    allInspectItemCategory, forwardSafetyScene, getAccessTokenForSendMsg, getChargeManWeChatId,
    sendMessage, getTeammateBySchoolAndTypeApi, getMultiroutepatrolAddressIsRelationApi, addOneMultiroutepatrolAddressApi, deleteOneMultiroutepatrolAddressApi
} from "../js/api.js";
import {
    patrolRouteBySchoolApi, updatePatrolRouteApi
} from "../js/api.js";
import {
    checkpointBySchoolAndTypeApi, getInspectItemPointRelationBySchoolApi, allCategoryApi,
    allCategoryItemApi, deleteInspectItemPointRelationApi, addInspectItemPointRelationApi,
    getInspectItemPointRelationDetailByCheckpointIdApi, getInspectItemFromManualWithTree,
    deleteInspectItemPointRelationByRelationIdApi, checkpointBySchoolAndTypeExceptExistApi,
    getInspectItemCheckpointRelationByCheckpointIdWithTree, updateInspectItemCheckpointRelation
} from "../js/api.js";
import {
    patrolPlanBySchoolApi, deletePatrolPlanApi, updatePatrolPlanApi, addPatrolPlanApi,
    teamOptionsBySchoolAndType
} from "../js/api.js";
import {
    inspectPlanMakeClassBySchoolApi, inspectPlanMakeByClassIdApi, addInspectPlanApi, updateAndAddInspectPlanApi,
    deleteInspectPlanBySymbolApi, updateInspectPlanApi, getInspectPlanItemBySymbol, getInspectPlanItemAndContentUpdate,
    getItemWithTreeForAddInspectPlanApi, getInspectPlanSearchApi, getExistCategoryBySchoolIdAip,
    getInspectSearchChartDataApi, allUserApi, getSafetySceneSearchApi, getSafetySceneSearchChartDataApi,
    getInspectPlanHistoryApi, addInspectPlanFromHistoryApi, deleteInspectPlanByClassIdApi, getInspectItemContentTree
} from "../js/api.js";
import {
    checkConditionBySchoolApi, punchCardDetialBySymbolApi, dataForDrawPunchCardApi
} from "../js/api.js";
import {
    inspectDealDetailByInspectPlanIdApi, inspectPlanClassBySchoolIdApi, inspectPlanByClassIdApi
} from "../js/api.js";
import {
    safetysceneBySchoolApi, updateSafetysceneApi, safetysceneDetailByIdApi
} from "../js/api.js";
import {
    listMenuByPermission
} from "../js/api.js";
import {
    getPatrolCountByDay, getInspectTimeByDay, getTroublePoint, getTroubleItem,
    getPatrolCountAll, getTodayInfo, getAllTimeInfo
} from "../js/api.js";
import {
    getDeviceInfoListApi, getHistoryTemperatureApi, getHistoryElectricApi, getRecentDeviceInfoApi, deleteGpsFireElectricApi, getUnDeployDiviceApi, addGpsFireElectricDeviceApi, updateGpsFireElectricDeviceApi
} from "../js/api.js";
import {
    getAllSmokeDeviceRecordBySchoolIdApi, getSearchSmokeDeviceRecordApi, getSingleSmokeDeviceRecordApi,
    getUpAndDownDeviceMessageApi, getFaceRecordByDepartmentApi, getFaceImageBasicManageApi, getDeviceEnterConditionByUserNumberApi, deleteFaceImageApi, deleteUpdateRecordApi
} from "../js/api.js";
import {
    getVisitorMessageApi, getVisitorrecordSearchApi, getVisitorTimeByDay, getTodayVisitorInfo, getVisitorNameToday, getVisitorNumRank
} from "../js/api.js";

import {
    getAllScoreDate, getScoreDetailByDate
} from "../js/api.js";
import {
    getMultiroutepatrolAddressBySchoolId, addMultiroutepatrolRouteName, addMultiroutepatrolRoute, getMultiroutepatrolRouteApi,
    getMultiroutepatrolAddressByRouteIdApi, updateRouteNameApi, deleteRouteByRouteIdApi
} from "../js/api.js";

import { batchImportInspectClassApi, batchImportInspectAddressAndInspectItemApi, batchImportInspectPlanApi } from "../js/api.js";

import { FormOutlined, EditOutlined } from '@ant-design/icons';

import moment from 'moment';
import { DragDropContext, DragSource, DropTarget } from "react-dnd";
import HTML5Backend from "react-dnd-html5-backend";
import update from "immutability-helper";
import { UrlPrefix, iconFontUrl, classMemberUploadTemplateUrl, wangGeGuiHuaUploadTemplateUrl, inspectPlanUploadTemplateUrl } from "../js/config.js";
import icon from "../img/icon.png";
// import echarts from 'echarts';
import * as echarts from 'echarts'
import { data } from "jquery";
// import { Player } from 'video-react';



import { gridStudentUrl, gridFiveOldStaffUrl, gridOutAdminUrl } from '../js/config.js'
import RViewerJS from "viewerjs-react";
import { exportExcel } from "../js/utils.js";

const { Search } = Input;
const FormItem = Form.Item;
const Option = Select.Option;
const SubMenu = Menu.SubMenu;
const { Content, Footer, Sider, Header } = Layout;
const { TreeNode } = Tree;
const Step = Steps.Step;
const TabPane = Tabs.TabPane;
const RangePicker = DatePicker.RangePicker;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});
// const echarts = require('echarts');

class SchoolSafetySupervisor extends Component {
    constructor(props) {
        super(props);
        let url = document.location.href;
        let page = url.split("/")[5];
        let defaultSelectedKeys;
        let defaultOpenKeys;
        switch (page) {
        case "teamassignment"://人员班组分配
            defaultOpenKeys = ""
            defaultSelectedKeys = "teamassignment"; break;
        case "patrolroute"://云巡更路线规划
            defaultOpenKeys = "patrol";
            defaultSelectedKeys = "patrolroute"; break;
        case "patrolplan"://云巡更计划制定
            defaultOpenKeys = "patrol";
            defaultSelectedKeys = "patrolplan"; break;
        case "patrocondition"://云巡更数据统计
            defaultOpenKeys = "patrol";
            defaultSelectedKeys = "patrocondition"; break;
        case "inspectwithcheckpoint"://隐患排查点规划
            defaultOpenKeys = "inspect";
            defaultSelectedKeys = "inspectwithcheckpoint"; break;
        case "inspectplan"://隐患排查计划制定
            defaultOpenKeys = "inspect";
            defaultSelectedKeys = "inspectplan"; break;
        case "inspectcondition"://校园巡查上报
            defaultOpenKeys = "inspect";
            defaultSelectedKeys = "inspectcondition"; break;
        case "safetyscene"://校园安全隐患上报
            defaultOpenKeys = "";
            defaultSelectedKeys = "safetyscene"; break;
        case "patrolcharts"://数据图表
            defaultOpenKeys = "charts";
            defaultSelectedKeys = "patrolcharts"; break;
        case "inspectcharts"://数据图表
            defaultOpenKeys = "charts";
            defaultSelectedKeys = "inspectcharts"; break;
        case "monitor"://用电安全漏电监测
            defaultOpenKeys = "electricalsafety";
            defaultSelectedKeys = "monitor"; break;
        case "electricityInquiry"://用电安全漏电查询
            defaultOpenKeys = "electricalsafety";
            defaultSelectedKeys = "electricityInquiry"; break;
        case "smokeDevice"://烟感设备
            defaultOpenKeys = "accessDevice";
            defaultSelectedKeys = "smokeDevice"; break;
        case "upAndDownDevice"://防撞柱设备
            defaultOpenKeys = "accessDevice";
            defaultSelectedKeys = "upAndDownDevice"; break;
        case "faceRecordDevice"://访客机设备
            defaultOpenKeys = "accessDevice";
            defaultSelectedKeys = "faceRecordDevice"; break;
        default:
            defaultOpenKeys = "charts";
            defaultSelectedKeys = "patrolcharts";
        }
        this.state = {
            defaultSelectedKeys: [defaultSelectedKeys],
            defaultOpenKeys: [defaultOpenKeys],
            collapsed: false,
            menuData: []
        };
        // console.log(this.props.location.state);
        console.log(sessionStorage.getItem("username"));
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        let departmentId = sessionStorage.getItem("departmentId");
        let identityId = sessionStorage.getItem("identityId");
        listMenuByPermission(departmentId, identityId)
            .then(res => {
                this.setState({
                    menuData: res.data
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    onCollapse = (collapsed) => {
        //console.log(collapsed);
        if (collapsed) {
            document.getElementById("logoName").style.display = "none";
        } else {
            document.getElementById("logoName").style.display = "inline";
        }
        this.setState({ collapsed });
    }

    logOff() {

        sessionStorage.setItem("username", null);
        sessionStorage.setItem("identityId", null);
        sessionStorage.setItem("departmentId", null);
        this.props.history.push("/");
    }

    jump = () => {
        let defaultOpenKeys = this.state.defaultOpenKeys;
        this.setState({
            defaultSelectedKeys: ["electricityInquiry"],
            // defaultOpenKeys: ["electricalsafety"]
        })
        console.log(this.state.defaultOpenKeys);
        console.log(["electricalsafety"].indexOf("electricalsafety"));
        console.log(this.state.defaultOpenKeys.indexOf("electricalsafety"));
        if (defaultOpenKeys.indexOf("electricalsafety") === -1) {
            this.setState({
                defaultOpenKeys: defaultOpenKeys.concat(["electricalsafety"]),
            })
        }
    }

    MenuChange = (item) => {
        this.setState({
            defaultSelectedKeys: [item.key],
        });
    }

    openMenu = (openKeys) => {
        console.log(openKeys);
        this.setState({
            defaultOpenKeys: openKeys,
        });
    };

    render() {
        const menu = this.state.menuData.map(val => {
            const subMenu = val.subMenu.map(subVal => {
                return (
                    <Menu.Item key={subVal.key}>
                        <Link to={subVal.route}>
                            <IconFont type={subVal.icon} className='icon' />
                            <span className="nav-text">{subVal.name}</span>
                        </Link>
                    </Menu.Item>
                )
            });
            return (
                val.subMenu.length == 0 ?
                    (
                        <Menu.Item key={val.key}>
                            <Link to={val.route}>
                                <IconFont type={val.icon} className='icon' />
                                <span className="nav-text">{val.name}</span>
                            </Link>
                        </Menu.Item>
                    ) :
                    (
                        <SubMenu
                            key={val.key}
                            title={
                                <span>
                                    <IconFont type={val.icon} className='icon' />
                                    <span>{val.name}</span>
                                </span>
                            }>
                            {subMenu}
                        </SubMenu>
                    )
            );
        });
        return (
            <Router basename="/school/safetysupervisor">
                <Layout>
                    <Sider
                        collapsible
                        collapsed={this.state.collapsed}
                        onCollapse={this.onCollapse}
                        width={256}
                        style={{
                            overflow: "auto",
                            height: "100vh",
                            left: 0,
                        }}>
                        <div className="logo" >
                            {/* <IconFont type="icon-anfang" className='icon' style={{ verticalAlign: "middle", }} /> */}
                            <img src={icon} className='icon' style={{
                                verticalAlign: "middle",
                                width: '30px',
                                height: '30px',
                                marginRight: '5px'
                            }} />
                            <div
                                id='logoName'
                                style={{ verticalAlign: 'middle', display: 'inline-block', paddingLeft: "5px" }}>
                                梯度智慧安监
                            </div>
                        </div>
                        <Menu
                            theme="dark"
                            mode="inline"
                            defaultSelectedKeys={this.state.defaultSelectedKeys}
                            defaultOpenKeys={this.state.defaultOpenKeys}
                            selectedKeys={this.state.defaultSelectedKeys}
                            openKeys={this.state.defaultOpenKeys}
                            onClick={(item) => this.MenuChange(item)}
                            onOpenChange={(openKeys) => this.openMenu(openKeys)}>
                            {menu}
                        </Menu>
                    </Sider>
                    <Layout style={{ height: "100vh" }}>
                        <Header style={{
                            background: '#fcfcfc',
                            padding: 0,
                            fontFamily: 'Microsoft Yahei, sans-serif',
                            fontSize: 15,
                            position: 'relative',
                            height: '64px',
                            lineHeight: '64px',
                        }}>
                            <div style={{ position: "absolute", top: 0, bottom: 0, left: 24, }}>
                                欢迎您！您的身份为<span style={{ color: '#1890ff' }}>安监主任</span>
                            </div>
                            <div style={{ position: "absolute", top: 0, bottom: 0, right: 24, }}>
                                <Dropdown overlay={
                                    <Menu>
                                        <Menu.Item>
                                            <a
                                                class='logOff'
                                                style={{ color: '#333333', padding: '5px 15px' }}
                                                onClick={() => this.logOff()}>
                                                <IconFont
                                                    type="icon-zhuxiaologout11" className='icon'
                                                    style={{ fontSize: '14px', verticalAlign: 'middle' }} />
                                                <span style={{ verticalAlign: 'middle', marginLeft: '2px' }}>退出登录</span>
                                            </a>
                                        </Menu.Item>
                                        <Menu.Item>
                                            <a
                                                class='logOff'

                                                style={{ color: '#333333', padding: '5px 15px' }}
                                                href={this.state.screenurl}>
                                                <IconFont
                                                    type="icon-zhuxiaologout11" className='icon'
                                                    style={{ fontSize: '14px', verticalAlign: 'middle' }} />
                                                <span style={{ verticalAlign: 'middle', marginLeft: '2px' }}>安防大屏</span>
                                            </a>
                                        </Menu.Item>


                                    </Menu>
                                }>
                                    <div
                                        className='dropdown'
                                        style={{
                                            padding: '0px 5px'
                                        }}>
                                        <IconFont
                                            style={{ fontSize: '28px', verticalAlign: 'middle' }}
                                            type="icon-touxiang-shi" className='icon' />
                                        <span style={{ marginLeft: '2px' }}>{sessionStorage.getItem("username")}</span>
                                    </div>
                                </Dropdown>
                            </div>
                        </Header>
                        <Content style={{ margin: "24px", overflow: "initial" }}>
                            <div
                                id="right"
                                style={{
                                    padding: 24,
                                    background: "#fff",
                                    height: "auto",
                                    marginBottom: 24
                                }}>
                                {/* <Switch>
                                    <Route path="/teamassignment" component={SchoolTeamAssignmentManager} />
                                    <Route path="/patrolroute" component={PatrolRouteManager} />
                                    <Route path="/patrolplan" component={SchoolPatrolPlanManager} />
                                    <Route path="/patrocondition" component={SchoolPatrolConditionManager} />
                                    <Routepath path="/inspectwithcheckpoint" component={SchoolInspectWithCheckpointManager} />
                                    <Route path="/inspectplan" component={SchoolInspectPlanManager} />
                                    <Route path="/inspectcondition" component={SchoolInspectConditionManager} />
                                    <Route path="/safetyscene" component={SchoolSafetySceneManager} />
                                    <Route path="/patrolcharts" component={PatrolCharts} />
                                    <Route path="/inspectcharts" component={InspectCharts} />
                                    <Route path="/monitor" render={(props) => (<MonitorTable jump={this.jump} {...props} />)} />
                                    <Route path="/electricityInquiry" component={Electricalsafety} />
                                    <Redirect path="/" to={{ pathname: '/patrolcharts' }} />
                                </Switch> */}
                            </div>
                            <div
                                style={{
                                    width: 'auto',
                                    height: 24,
                                    background: '#f0f2f5'
                                }}
                            ></div>
                        </Content>
                    </Layout>
                </Layout>
            </Router>
        );
    }
}
//---------------------------------------------------------------------------

class SchoolTeamAssignmentManager extends Component {
    constructor(props) {
        super(props);

        this.state = {
            addTeamVisible: false,
            addTeammateVisible: false,
            updateTeamVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            data: [],
            outerData: [],
            teamTypeFilter: [
                { text: '巡更', value: 1 },
                { text: '巡检', value: 2 },
            ],
            filteredInfo: null,
            sortedInfo: null,

            fileList: [],
            uploading: false,
            addVisible: false,
        };

    }

    componentDidMount() {
        this.refreshData();
    }


    refreshData() {
        this.setState({
            tableLoading: true,
            outerData: [],
            teamInform: []
        });
        let outerColumnData = [];
        let teamInformation = [];
        allTeamBySchoolApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    outerColumnData.push({
                        key: index + 1,
                        id: item.id,
                        teamName: item.name,
                        chargeMan: item.realName,
                        chargeManId: item.chargeManId,
                        chargeManShow: item.realName ? item.realName : "",
                        startTime: item.startTime,
                        endTime: item.endTime,
                        teamType: item.type,
                        teamTypeName:item.type == 1 ? "巡更" : "巡检",
                        workTime: item.startTime + '~' + item.endTime,
                        categoryId: item.categoryId,
                        categoryName: item.category,
                    });
                });

                teamInformation = outerColumnData.slice();
                for(let i=0;i<teamInformation.length;i++)
                {
                    teamInformation[i].chargeManShow = []
                    getTeammateByTeamIdApi(teamInformation[i].id)
                    .then((res) => {
                        res.data.forEach((item, index) => {
                            teamInformation[i].chargeManShow.push(item.realName);
                        });
                    })
                }
                
                this.setState({
                    outerData: outerColumnData,
                    teamInform: teamInformation,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    showClassByMemberName(name){
        if(name=="")
        {
            this.refreshData();
        }
        else
        {
            this.setState({
                tableLoading: true,
                outerData: [],
                teamInform: []
            });
            let outerColumnData = [];
            let teamInformation = []
            getAllClassByMemberNameApi(sessionStorage.getItem("departmentId"), name)
                .then((res) => {    
                    res.data.forEach((item, index) => {
                        //console.log("getAllUser", item);
                        outerColumnData.push({
                            key: index + 1,
                            id: item.id,
                            teamName: item.name,
                            chargeMan: item.realName,
                            chargeManId: item.chargeManId,
                            chargeManShow: item.realName ? item.realName : "",
                            startTime: item.startTime,
                            endTime: item.endTime,
                            teamType: item.type,
                            teamTypeName:item.type == 1 ? "巡更" : "巡检",
                            workTime: item.startTime + '~' + item.endTime,
                            categoryId: item.categoryId,
                            categoryName: item.category,
                        });
                    });

                    teamInformation = outerColumnData.slice();
                    for(let i=0;i<teamInformation.length;i++)
                    {
                        teamInformation[i].chargeManShow = []
                        getTeammateByTeamIdApi(teamInformation[i].id)
                        .then((res) => {
                            res.data.forEach((item, index) => {
                                teamInformation[i].chargeManShow.push(item.realName);
                            });
                        })
                    }
                

                    this.setState({
                        outerData: outerColumnData,
                        teamInform: teamInformation,
                        tableLoading: false
                    });                
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
        }
    }

    //点击表格中 添加班次 触发的操作
    showAddTeamModal() {

        this.setState({
            addTeamVisible: true,
        });
    }




    //批量导入巡检班组
    batchImportInspectClass() {
        console.log("===============批量导入巡检班组====================")
        this.setState({
            addVisible: true,
            fileList: [],
        });
    }

    handleCancel = e => {

        this.setState({
            addVisible: false,
            fileList: [],
            uploading: false
        });
    };


    handleUpload = (e) => {
        let schoolId = sessionStorage.getItem("departmentId")
        const { fileList, buttonFlag } = this.state;
        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('upfile', file);
        });


        this.setState({
            uploading: true,
        });

        formData.append('schoolId', schoolId)
        batchImportInspectClassApi(formData).then((res) => {
            if (res.data == 'success') {
                this.setState({
                    fileList: [],
                    uploading: false,
                    addVisible: false
                });
                this.refreshData();
                message.success('导入成功！');
            }else if(res.data == 'errorUserName'){
                message.error("该行班组成员不存在、不是巡检员或安监主任，请仔细检查该行班组成员。", 5);
            }else {
                this.setState({
                    uploading: false,
                });
                //message.error(res.data);
                message.error("第"+res.data+"行出现空格等特殊字符，请仔细检查该行。", 5);
                // message.error("导入失败，请检查文件！")
            }
            this.setState({
                fileList: [],
                uploading: false,
            });
        })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            })

    }



    //点击表格中 添加人员 触发的操作
    showAddTeammateModal(teamId, teamType) {
        this.setState({
            currentTeamType: teamType,
            currentTeamId: teamId,
            addTeammateVisible: true,

        });
    }

    //点击表格中 修改 触发的操作
    showUpdateTeamModal(teamId, teamName, chargeMan, chargeManId, startTime, endTime, teamType, categoryId) {
        this.setState({
            updateTeamVisible: true,
            currentTeamId: teamId,
            currentTeamName: teamName,
            currentChargeMan: chargeMan,
            currentChargeManId: chargeManId,
            currentStartTime: startTime,
            currentEndTime: endTime,
            currentTeamType: teamType,
            currentCategoryId: categoryId
        });
    }

    handleDeleteTeam(id) {
        this.setState({
            tableLoading: true
        });
        deleteTeamApi(id)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.state.outerData.some((item, i) => {
                        if (item.id == id) {
                            this.state.outerData.splice(i, 1)
                        }
                    })
                    this.setState({
                        tableLoading: false
                    });
                    // this.refreshData();
                }
                else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }



    //添加新的班次 点击提交后的动作
    handleAddTeamClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addTeamFormValue;
        val.validateFields((err, values) => {
            console.log("test", values)
            if (!err) {
                values.workStartTime = moment(values.workStartTime).format('HH:mm:ss');
                values.workEndTime = moment(values.workEndTime).format('HH:mm:ss');
                if (values.teamType == 2) {//巡检
                    values.workStartTime = null;
                    values.workEndTime = null;
                }
                if (values.teamType == 1) {//巡逻
                    values.categoryId = null;
                }

                addTeamApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addTeamVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            this.child.refreshData();
                            //this.refs.teammateTableRefresh.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addTeamVisible: true,
                                confirmLoading: false,
                                msg: "添加失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //添加指定班次的人员 点击提交按钮后的操作
    handleAddTeammateClick(teamId) {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addTeammateFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                addTeammateApi(teamId, values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addTeammateVisible: false,
                                confirmLoading: false
                            });
                            // this.refreshData();
                            //this.teammateTableFormRef.refreshData();
                            //this.refs.teammateTableRefresh.refreshData();
                            this.child.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addTeammateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //修改班次信息 点击提交按钮后的操作
    handleUpdateTeamClick(teamId) {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.updateTeamFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                values.workStartTime = moment(values.workStartTime).format('HH:mm:ss');
                values.workEndTime = moment(values.workEndTime).format('HH:mm:ss');
                //console.log(values);
                // if (values.workStartTime != null && values.workEndTime != null
                //     && values.workStartTime >= values.workEndTime && values.teamType == 1) {
                //     this.setState({
                //         alertVisible: true,
                //         updateTeamVisible: true,
                //         confirmLoading: false,
                //         msg: "修改失败,下班时间不可早于上班时间!"
                //     });
                // } else {
                updateTeamApi(parseInt(sessionStorage.getItem("departmentId")), teamId, values)
                    .then((res) => {
                        if (res.data == "success") {
                            message.success("更新成功!");
                            this.setState({
                                updateTeamVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            this.child.refreshData();
                            //this.refs.teammateTableRefresh.refreshData();
                            val.resetFields();
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                updateTeamVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    //关闭添加班组模态框
    handleAddTeamCancel() {
        let val = this.refs.addTeamFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addTeamVisible: false
        });
    }

    //关闭添加班组成员模态框
    handleAddTeammateCancel() {
        let val = this.refs.addTeammateFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addTeammateVisible: false
        });
    }

    //关闭更新班组信息模态框
    handleUpdateTeamCancel() {
        let val = this.refs.updateTeamFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            updateTeamVisible: false
        });
    }


    onRef = (ref) => {
        this.child = ref
    }


    render() {

        const onSearchMember = (value) => this.showClassByMemberName(value);

        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        // Excel标题
        let header = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "班次名称",
                dataIndex: "teamName",
                key: "teamName"
            },
            {
                title: "班组人员",
                dataIndex: "chargeManShow",
                key: "chargeManShow",
            },
            {
                title: "班次类型",
                dataIndex: "teamTypeName",
                key: "teamTypeName"
            }
        ]
        const { uploading, fileList } = this.state;
        const props = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: file => {

                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));

                return false;
            },
            fileList,
        }

        const outerColumns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "班次名称",
            dataIndex: "teamName",
            key: "teamName",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.teamName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "负责人",
            dataIndex: "chargeMan",
            key: "chargeMan",
            render: (text, record) => {
                //console.log(record.chargeMan);
                if (record.chargeMan == null) {
                    return '-';
                } else {
                    return record.chargeMan;
                }
            }
        }, {
            title: "工作时间",
            dataIndex: "workTime",
            key: "workTime",
            render: (text, record) => {
                //console.log(record);
                if (record.startTime == null && record.endTime == null) {
                    return '-';
                } else {
                    return record.workTime;
                }
            }
        }, {
            title: "班次类型",
            dataIndex: "teamType",
            key: "teamType",
            render: (text, record) => {
                //console.log(record);
                if (record.teamType == 1) {
                    return (
                        <div>
                            <Tag color={'magenta'}>{'巡更'}</Tag>
                        </div>
                    );
                } else if (record.teamType == 2) {
                    let tags = record.categoryName.map((row, index) => <Tag color={'#87d068'}>{row}</Tag>)
                    return (
                        <div>
                            <Tag color={'blue'}>{'巡检'}</Tag>
                            {tags}
                        </div>
                    );
                }

            },
            filters: this.state.teamTypeFilter,
            filteredValue: filteredInfo.teamType || null,
            onFilter: (value, record) => record.teamType == value,
            filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
        }, {
            title: "操作详情",
            key: "action",
            render: (text, record) => (
                <span>
                    <a href="javascript:;" onClick={this.showAddTeammateModal.bind(this, record.id, record.teamType)}>添加人员</a>
                    <Divider type="vertical" />
                    <a href="javascript:;" onClick={this.showUpdateTeamModal.bind(this, record.id,
                        record.teamName, record.chargeMan, record.chargeManId,
                        record.startTime, record.endTime, record.teamType, record.categoryId)}>修改</a>
                    <Divider type="vertical" />
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDeleteTeam(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];

        // console.log(this.state.outerData);

        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Modal
                        destroyOnClose={true}
                        title={"新增班组"}
                        visible={this.state.addTeamVisible}
                        onCancel={this.handleAddTeamCancel.bind(this)}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                onClick={this.handleAddTeamClick.bind(this)}>提交</Button>
                        ]}
                    >
                        <AddTeamForm ref="addTeamFormValue" />
                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                    <Modal
                        destroyOnClose={true}
                        title={"添加班组成员"}
                        visible={this.state.addTeammateVisible}
                        onCancel={this.handleAddTeammateCancel.bind(this)}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                onClick={this.handleAddTeammateClick.bind(this, this.state.currentTeamId)}>提交</Button>
                        ]}
                    >
                        <AddTeammateForm ref="addTeammateFormValue"
                            currentTeamId={this.state.currentTeamId}
                            currentTeamType={this.state.currentTeamType} />
                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                    <Modal
                        destroyOnClose={true}
                        title={"修改班组信息"}
                        visible={this.state.updateTeamVisible}
                        onCancel={this.handleUpdateTeamCancel.bind(this)}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                onClick={this.handleUpdateTeamClick.bind(this, this.state.currentTeamId)}>提交</Button>
                        ]}
                    >
                        <UpdateTeamForm ref="updateTeamFormValue"
                            currentTeamId={this.state.currentTeamId}
                            currentTeamName={this.state.currentTeamName}
                            currentChargeMan={this.state.currentChargeMan}
                            currentChargeManId={this.state.currentChargeManId}
                            currentStartTime={this.state.currentStartTime}
                            currentEndTime={this.state.currentEndTime}
                            currentTeamType={this.state.currentTeamType}
                            currentCategoryId={this.state.currentCategoryId}
                        />
                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                    <Button type="primary" onClick={this.showAddTeamModal.bind(this)} size="large">
                        <Icon type="usergroup-add" theme="outlined" />新添班组
                    </Button>

                    <Button type="primary" onClick={() => this.batchImportInspectClass()} size="large" style={{ marginLeft: '20px' }}>
                        <Icon type="usergroup-add" theme="outlined" />批量导入
                    </Button>



                    <Button href={classMemberUploadTemplateUrl} style={{ marginLeft: 15 }} size="large"><Icon type="download" />下载巡检班组导入模板</Button>

                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"导入班组人员信息"}
                                visible={this.state.addVisible}
                                onCancel={this.handleCancel}
                                closable
                                maskClosable={false}
                                footer={[]}
                                centered={true}
                                style={{ marginLeft: 15 }}
                            >
                                <Spin tip="导入数据时间较长，请耐心等待！" spinning={this.state.uploading} size="large">
                                    <Upload {...props}>
                                        <Button >
                                            <Icon type="upload" />选择文件
                                        </Button>
                                    </Upload>

                                    <Button
                                        type="primary"
                                        onClick={this.handleUpload}
                                        disabled={fileList.length === 0}
                                        loading={uploading}
                                        style={{ marginTop: 16 }}
                                    >
                                        {uploading ? '正在上传' : '开始上传'}
                                    </Button>
                                </Spin>
                            </Modal>) : null
                    }


                    <Button style={{ marginLeft: '20px' }} onClick={this.clearAll}>
                        <Icon type="delete" theme="outlined" />清除筛选
                    </Button>

                    <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                        exportExcel(header, this.state.teamInform, "班组信息.xlsx")
                    }}>班组信息导出Excel
                    </Button>
                    <Search
                        placeholder=""
                        allowClear
                        enterButton="成员查询"
                        size="middle"
                        style={{
                            width: 200, 
                            marginLeft: '20px',
                            marginTop: '5px'}}
                        onSearch={onSearchMember}
                    />
                </div>
                <Table
                    dataSource={this.state.outerData}
                    columns={outerColumns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    expandedRowRender={(record) => {
                        return (
                            <TeammateTable
                                //wrappedComponentRef={(inst) => this.teammateTableFormRef = inst}
                                //ref="teammateTableRefresh"
                                onRef={this.onRef}
                                teamId={record.id}
                                that={this} />)
                    }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </div>
        )
    }
}

class TeammateTable extends Component {
    constructor(props) {
        super(props);
        const innerColumns = [{
            title: '用户名',
            dataIndex: 'username',
            key: 'userName',
            width: '30%',
        }, {
            title: '真实姓名',
            dataIndex: 'realname',
            key: 'realName',
            width: '20%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa' }} />,
            onFilter: (value, record) => record.realname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: '联系电话',
            dataIndex: 'phone',
            key: 'phone',
            width: '30%',
        },
        {
            title: "操作详情",
            key: "action",
            width: '20%',
            render: (text, record) => (
                <span>
                    {
                        record.key == 1 ?
                            (<span>★负责人★&nbsp;</span>) : (
                                <Popconfirm title="确定升为负责人？将顶替原有负责人。" okText="确定" cancelText="取消"
                                    onConfirm={() => this.handleSetChargeMan(props.teamId, record.id)}>
                                    <a href="#">升为负责人</a>
                                </Popconfirm>
                            )
                    }
                    <Divider type="vertical" />
                    <Popconfirm title="提示：班组成员只有一人时，删除该成员，本班组和巡更、巡检计划将一并删除，删除后需要重新添加班组，制定计划，确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDeleteTeammate(props.teamId, record.id, record.realname)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            teamId: props.teamId,
            innerColumns: innerColumns,
            that: props.that
        }
    }

    componentDidMount() {
        this.refreshData();
        this.props.onRef(this);
    }

    componentWillReceiveProps(props) {
        this.setState({
            teamId: props.teamId,
            that: props.that,
        });
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        getTeammateByTeamIdApi(this.state.teamId)
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    innerData.push({
                        key: index + 1,
                        id: item.id,
                        username: item.username,
                        realname: item.realName,
                        phone: item.phone
                    });
                });
                // console.log(innerData)
                this.setState({
                    innerData: innerData,
                    tableLoading: false
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }


    handleDeleteTeammate(teamId, userId) {
        // 删除操作之前班组人数
        let teammateNum = this.state.innerData.length
        deleteTeammateApi(teamId, userId)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                    // 删除操作之前班组人数为1，且删除操作成功后，该班组不存在，进行刷新
                    if(teammateNum == 1)
                    {
                        this.state.that.refreshData();
                    }   
                }else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSetChargeMan(teamId, userId) {
        setChargeManApi(teamId, userId)
            .then((res) => {
                if (res.data == "success") {
                    message.success("设置成功!");
                    this.refreshData();
                    // this.state.that.refreshData();
                } else {
                    message.error('设置失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    render() {
        return (
            <Table
                columns={this.state.innerColumns}
                dataSource={this.state.innerData}
                pagination={false}
                size='small'
                loading={this.state.tableLoading}
                locale={{ emptyText: '暂无数据' }}
                bordered={true}
                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
            />
        )
    }
}

class addTeamForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            allTeamType: [{
                value: 1,
                text: '巡更'
            }, {
                value: 2,
                text: '巡检'
            }],
            nowType: 1,
            nowCategory: 1,
            allCategory: [],
            availablePeople: [],
        };
    }

    componentDidMount() {
        allCategoryApi()
            .then((res) => {
                let categories = [];
                res.data.forEach((item, index) => {
                    let temp = {
                        text: item.category,
                        value: item.id,
                    }
                    categories.push(temp);
                });
                this.setState({
                    allCategory: categories
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getTeammateBySchoolAndTypeApi(
            parseInt(sessionStorage.getItem("departmentId")), this.state.nowType)
            .then((res) => {
                let allAvailablePeople = [];
                res.data.forEach((item, index) => {
                    allAvailablePeople.push({
                        realname: item.realName,
                        value: item.id,
                        username: item.username
                    });
                });
                this.setState({
                    availablePeople: allAvailablePeople
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    teamTypeSelectOnChange = (value) => {
        //console.log(value);
        this.setState({
            nowType: value,
            availablePeople: []
        });
        this.props.form.setFieldsValue({
            peopleToJoinTeam: []
        });
        getTeammateBySchoolAndTypeApi(
            parseInt(sessionStorage.getItem("departmentId")), value)
            .then((res) => {
                let allAvailablePeople = [];
                res.data.forEach((item, index) => {
                    allAvailablePeople.push({
                        realname: item.realName,
                        value: item.id,
                        username: item.username
                    });
                });
                this.setState({
                    availablePeople: allAvailablePeople
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    categorySelectOnChange = (value) => {
        //console.log(value);
        this.setState({
            nowCategory: value
        })
    }



    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        const allTeamTypeOptions = this.state.allTeamType.map((d, index) =>
            <Option value={d.value} key={index}>{d.text}</Option>);
        const allCategoryOptions = this.state.allCategory.map((d, index) =>
            <Option value={d.value} key={index}>{d.text}</Option>);
        const availablePeopleOptions = this.state.availablePeople.map((d, index) =>
            <Option value={d.value} key={index}>{d.username + ' - ' + d.realname}</Option>);

        const formInspect = (
            <Form>
                <FormItem
                    label='班次名称'
                    {...formItemLayout}>
                    {getFieldDecorator("teamName", {
                        initialValue: "",
                        rules: [{
                            required: true,
                            message: "请输入班次名称!"
                        }]
                    })(
                        <Input
                            size="large"
                            placeholder="班次名称"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='班次类型'
                    {...formItemLayout}>
                    {getFieldDecorator("teamType", {
                        initialValue: this.state.nowType,
                        rules: [{
                            required: true,
                            message: "请选择班次类型!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="班次类型"
                            onChange={this.teamTypeSelectOnChange}>
                            {allTeamTypeOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='巡检类别'
                    {...formItemLayout}>
                    {getFieldDecorator("categoryId", {
                        //initialValue: this.state.nowCategory,
                        rules: [{
                            required: (this.state.nowType == 2) ? (true) : (false),
                            message: "请选择巡检类别!"
                        }]
                    })(
                        <Select
                            mode="multiple"
                            size="large"
                            placeholder="巡检类别"
                            disabled={(this.state.nowType == 1) ? (true) : (false)}
                            onChange={this.categorySelectOnChange}>
                            {allCategoryOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='班组成员'
                    {...formItemLayout}>
                    {getFieldDecorator("peopleToJoinTeam", {
                        initialValue: [],
                        rules: [{
                            required: true,
                            message: "请选择添加人员!"
                        }]
                    })(
                        <Select
                            mode="multiple"
                            size="large"
                            placeholder="第一人默认设为负责人"
                            showSearch
                            filterOption={(input, option) =>{
                                console.log(input, option)
                                return  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }}
                            
                        >
                            {availablePeopleOptions}
                        </Select>
                    )}
                </FormItem>
            </Form>
        );

        const formPatrol = (
            <Form>
                <FormItem
                    label='班次名称'
                    {...formItemLayout}>
                    {getFieldDecorator("teamName", {
                        initialValue: "",
                        rules: [{
                            required: true,
                            message: "请输入班次名称!"
                        }]
                    })(
                        <Input
                            size="large"
                            placeholder="班次名称"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='班次类型'
                    {...formItemLayout}>
                    {getFieldDecorator("teamType", {
                        initialValue: this.state.nowType,
                        rules: [{
                            required: true,
                            message: "请选择班次类型!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="班次类型"
                            onChange={this.teamTypeSelectOnChange}>
                            {allTeamTypeOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='上班时间'
                    {...formItemLayout}>
                    {getFieldDecorator("workStartTime", {
                        //initialValue: "",
                        rules: [{
                            required: (this.state.nowType == 1) ? (true) : (false),
                            message: "请输入上班时间!"
                        }]
                    })(
                        <TimePicker
                            size="large"
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="上班时间"
                            disabled={(this.state.nowType == 2) ? (true) : (false)}
                        />
                    )}
                </FormItem>
                <FormItem
                    label='下班时间'
                    {...formItemLayout}>
                    {getFieldDecorator("workEndTime", {
                        //initialValue: "",
                        rules: [{
                            required: (this.state.nowType == 1) ? (true) : (false),
                            message: "请输入下班时间!"
                        }]
                    })(
                        <TimePicker
                            size="large"
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="下班时间"
                            disabled={(this.state.nowType == 2) ? (true) : (false)}
                        />
                    )}
                </FormItem>
                <FormItem
                    label='班组成员'
                    {...formItemLayout}>
                    {getFieldDecorator("peopleToJoinTeam", {
                        initialValue: [],
                        rules: [{
                            required: true,
                            message: "请选择添加人员!"
                        }]
                    })(
                        <Select
                            mode="multiple"
                            size="large"
                            placeholder="第一人默认设为负责人"
                            optionFilterProp="children"
                            showSearch
                            filterOption={(input, option) =>{
                                console.log(input, option)
                                return  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }}
                        >
                            {availablePeopleOptions}
                        </Select>
                    )}
                </FormItem>
            </Form>
        );

        const realForm = this.state.nowType == 1 ? formPatrol : formInspect;

        return (realForm)
    }
}
const AddTeamForm = Form.create()(addTeamForm);

class addTeammateForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentTeamType: props.currentTeamType,
            currentTeamId: props.currentTeamId,
            allAvailablePeople: []

        };
    }

    componentDidMount() {
        const allAvailablePeople = [];
        getallAvailablePeopleByTeamIdApi(this.state.currentTeamId, this.state.currentTeamType)
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    allAvailablePeople.push({
                        realname: item.realName,
                        value: item.id,
                        username: item.username
                    });
                });
                this.setState({
                    allAvailablePeople: allAvailablePeople
                })
            })

    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const allAvailablePeopleOptions = this.state.allAvailablePeople.map((d, index) => <Option value={d.value} key={index}>{d.username + ' - ' + d.realname}</Option>);
        return (
            <Form>
                <FormItem>
                    {getFieldDecorator("peopleToJoinTeam", {
                        initialValue: [],
                        rules: [{
                            required: true,
                            message: "请选择添加人员!"
                        }]
                    })(
                        <Select
                            mode="multiple"
                            size="large"
                            placeholder="添加人员"
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>{
                                console.log(input, option)
                                return  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }}>
                            {allAvailablePeopleOptions}
                        </Select>
                    )}
                </FormItem>
            </Form>
        )
    }
}
const AddTeammateForm = Form.create()(addTeammateForm);


class updateTeamForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentTeamId: props.currentTeamId,
            currentTeamName: props.currentTeamName,
            currentChargeMan: props.currentChargeMan,
            currentChargeManId: props.currentChargeManId,
            currentStartTime: props.currentStartTime,
            currentEndTime: props.currentEndTime,
            currentTeamType: props.currentTeamType,
            currentCategoryId: props.currentTeamType == 1 ? (undefined) : (props.currentCategoryId.map(Number)),

            allTeammate: [],
            allTeamType: [{
                value: 1,
                text: '巡更'
            }, {
                value: 2,
                text: '巡检'
            }],
            allCategory: [],
        };
        //console.log(this.state)
    }

    componentDidMount() {
        let allTeammate = [];
        getTeammateByTeamIdApi(this.state.currentTeamId)
            .then((res) => {
                //console.log(res);
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    allTeammate.push({
                        text: item.realName,
                        value: item.id,
                        username: item.username
                    });
                    this.setState({
                        allTeammate: allTeammate
                    })
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
        //console.log(allTeammate);
        allCategoryApi()
            .then((res) => {
                let categories = [];
                res.data.forEach((item, index) => {
                    let temp = {
                        text: item.category,
                        value: item.id,
                    }
                    categories.push(temp);
                });
                this.setState({
                    allCategory: categories
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }



    render() {
        const { getFieldDecorator } = this.props.form;
        const allTeamTypeOptions = this.state.allTeamType.map((d, index) =>
            <Option value={d.value} key={index}>{d.text}</Option>);

        const allTeammateOptions = this.state.allTeammate.map((d, index) =>
            <Option value={d.value} key={index}>{d.username + ' - ' + d.text}</Option>);

        const allCategoryOptions = this.state.allCategory.map((d, index) =>
            <Option value={d.value} key={index}>{d.text}</Option>);
        //console.log('111' + allTeammateOptions);
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        let formPatrol = (
            <Form>
                <FormItem
                    label='班次名称'
                    {...formItemLayout}>
                    {getFieldDecorator("teamName", {
                        initialValue: this.state.currentTeamName,
                        rules: [{
                            required: true,
                            message: "请输入班次名称!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="班次名称"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='班次类型'
                    {...formItemLayout}>
                    {getFieldDecorator("teamType", {
                        initialValue: this.state.currentTeamType,
                        rules: [{
                            required: true,
                            message: "请输入班次类型!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="班次类型"
                            disabled={true}>
                            {allTeamTypeOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='上班时间'
                    {...formItemLayout}>
                    {getFieldDecorator("workStartTime", {
                        initialValue: moment(this.state.currentStartTime, 'HH:mm:ss'),
                        rules: [{
                            required: (this.state.currentTeamType == 1) ? (true) : (false),
                            message: "请输入上班时间!"
                        }]
                    })(
                        <TimePicker
                            size="large"
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="上班时间"
                            disabled={(this.state.currentTeamType == 2) ? (true) : (false)}
                        />
                    )}
                </FormItem>
                <FormItem
                    label='下班时间'
                    {...formItemLayout}>
                    {getFieldDecorator("workEndTime", {
                        initialValue: moment(this.state.currentEndTime, 'HH:mm:ss'),
                        rules: [{
                            required: (this.state.currentTeamType == 1) ? (true) : (false),
                            message: "请输入下班时间!"
                        }]
                    })(
                        <TimePicker
                            size="large"
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="下班时间"
                            disabled={(this.state.currentTeamType == 2) ? (true) : (false)}
                        />
                    )}
                </FormItem>
                <FormItem
                    label='负责人'
                    {...formItemLayout}>
                    {getFieldDecorator("chargeManId", {
                        initialValue: this.state.currentChargeManId,
                        rules: [{
                            required: false,
                            message: "请选择班组负责人!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="负责人">
                            {allTeammateOptions}
                        </Select>
                    )}
                </FormItem>
            </Form>
        );

        let formInspect = (
            <Form>
                <FormItem
                    label='班次名称'
                    {...formItemLayout}>
                    {getFieldDecorator("teamName", {
                        initialValue: this.state.currentTeamName,
                        rules: [{
                            required: true,
                            message: "请输入班次名称!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="班次名称"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='班次类型'
                    {...formItemLayout}>
                    {getFieldDecorator("teamType", {
                        initialValue: this.state.currentTeamType,
                        rules: [{
                            required: true,
                            message: "请输入班次类型!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="班次类型"
                            disabled={true}>
                            {allTeamTypeOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='巡检类别'
                    {...formItemLayout}>
                    {getFieldDecorator("categoryId", {
                        // initialValue: this.state.currentCategoryId,
                        rules: [{
                            required: (this.state.currentTeamType == 2) ? (true) : (false),
                            message: "请选择巡检类别!"
                        }]
                    })(
                        <Select
                            mode="multiple"
                            size="large"
                            placeholder="巡检类别"
                            disabled={(this.state.currentTeamType == 1) ? (true) : (false)}>
                            {allCategoryOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='负责人'
                    {...formItemLayout}>
                    {getFieldDecorator("chargeManId", {
                        initialValue: this.state.currentChargeManId,
                        rules: [{
                            required: false,
                            message: "请选择班组负责人!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="负责人">
                            {allTeammateOptions}
                        </Select>
                    )}
                </FormItem>
            </Form>
        );

        let realForm = this.state.currentTeamType == 1 ? formPatrol : formInspect;

        return (realForm)
    }
}
const UpdateTeamForm = Form.create()(updateTeamForm);


//---------------------------------------------------------------------------

function dragDirection(
    dragIndex,
    hoverIndex,
    initialClientOffset,
    clientOffset,
    sourceClientOffset,
) {
    const hoverMiddleY = (initialClientOffset.y - sourceClientOffset.y) / 2;
    const hoverClientY = clientOffset.y - sourceClientOffset.y;
    if (dragIndex < hoverIndex && hoverClientY > hoverMiddleY) {
        return "downward";
    }
    if (dragIndex > hoverIndex && hoverClientY < hoverMiddleY) {
        return "upward";
    }
}

class BodyRow extends Component {
    render() {
        const {
            isOver,
            connectDragSource,
            connectDropTarget,
            moveRow,
            dragRow,
            clientOffset,
            sourceClientOffset,
            initialClientOffset,
            ...restProps
        } = this.props;
        const style = { ...restProps.style, cursor: "move" };

        let className = restProps.className;
        if (isOver && initialClientOffset) {
            const direction = dragDirection(
                dragRow.index,
                restProps.index,
                initialClientOffset,
                clientOffset,
                sourceClientOffset
            );
            if (direction === "downward") {
                className += " drop-over-downward";
            }
            if (direction === "upward") {
                className += " drop-over-upward";
            }
        }

        return connectDragSource(
            connectDropTarget(
                <tr {...restProps} className={className} style={style} />
            )
        );
    }
}

const rowSource = {
    beginDrag(props) {
        return {
            index: props.index
        };
    }
};

const rowTarget = {
    drop(props, monitor) {
        const dragIndex = monitor.getItem().index;
        const hoverIndex = props.index;

        // Don't replace items with themselves
        if (dragIndex === hoverIndex) {
            return;
        }

        // Time to actually perform the action
        props.moveRow(dragIndex, hoverIndex);

        // Note: we're mutating the monitor item here!
        // Generally it's better to avoid mutations,
        // but it's good here for the sake of performance
        // to avoid expensive index searches.
        monitor.getItem().index = hoverIndex;
    }
};

const DragableBodyRow = DropTarget("row", rowTarget, (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
    sourceClientOffset: monitor.getSourceClientOffset()
}))(
    DragSource("row", rowSource, (connect, monitor) => ({
        connectDragSource: connect.dragSource(),
        dragRow: monitor.getItem(),
        clientOffset: monitor.getClientOffset(),
        initialClientOffset: monitor.getInitialClientOffset()
    }))(BodyRow)
);

class addAddressForm extends Component {
    constructor(props) {
        super(props);

        this.state = {
            confirmLoading: false,
            patrolRoute: [],
            patrolAddress: []
        }
    }

    componentDidMount() {
        getMultiroutepatrolRouteApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    patrolRoute: res.data
                })
            })

        getMultiroutepatrolAddressBySchoolId(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    patrolAddress: res.data.patrolAddress
                })
                console.log("patrolAddress", this.state.patrolAddress)
            })

    }
    handleChange = (value, event) => {
        console.log(value)
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        const allAddressTypeOptions = this.state.patrolRoute.map((d, index) =>
            <Option value={d.id} key={d.id}>{d.routeName}</Option>);

        const patrolAddressIsRelationOptions = this.state.patrolAddress.map(v => {
            return (
                <Option value={v.addressId + "-" + v.checkPointId} key={v.checkPointId}>{v.name}</Option>
            )
        })

        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='巡更路线名称'
                    {...formItemLayout}>
                    {getFieldDecorator("routeNameId", {
                        rules: [{
                            required: true,
                            message: "请选择巡更路线!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="巡更路线">
                            {allAddressTypeOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='巡更地址'
                    {...formItemLayout}>
                    {getFieldDecorator("addressIdAndChecPointId", {
                        rules: [{
                            required: true,
                            message: '请选择巡更地址！',
                        }]
                    })(
                        <Select
                            mode="multiple"
                            allowClear
                            size="large"
                            placeholder="巡更地址"
                            onChange={this.handleChange}>
                            {patrolAddressIsRelationOptions}
                        </Select>
                    )}
                </FormItem>
            </Form>
        )
    }
}
const AddAddressForm = Form.create()(addAddressForm);

class SchoolPatrolRouteManager extends Component {
    constructor(props) {
        super(props);
        this.columns = [
            {
                title: "巡更次序",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "地址",
                dataIndex: "address",
                key: "address"
            },
            {
                title: "设备编号",
                dataIndex: "macAddress",
                key: "macAddress"
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDelete(record)}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }
        ];
        this.state = {
            alertVisible: false,
            confirmLoading: false,
            isLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            dataLength: 0,
            addPatrolRouteVisible: false,
            patrolRoute: [],
            tableLoading1: false,
            routeName: "",
            routeNameId: 0,
            columnData: [],
            updateVisible: false,
            routeNameIdByAdd: []
        };

    }
    componentWillMount() {
        console.log("--------------------will")
    }

    componentDidMount() {
        this.setState({
            confirmLoading: true
        })
        this.refreshData2()
    }

    handleDelete(value) {
        let routeNameId = value.routeNameId
        let addressName = value.address
        deleteOneMultiroutepatrolAddressApi(parseInt(sessionStorage.getItem("departmentId")), routeNameId, addressName)
            .then((res) => {
                if (res.data == "success") {
                    this.setState({
                        routeNameIdByAdd: value.routeNameId,
                        tableLoading: true
                    })
                    let columnData = []
                    getMultiroutepatrolAddressByRouteIdApi(parseInt(sessionStorage.getItem("departmentId")), this.state.routeNameIdByAdd)
                        .then((res) => {
                            res.data.forEach((item, index) => {
                                columnData.push({
                                    key: index + 1,
                                    id: item.id,
                                    checkPointId: item.checkPointId,
                                    routeName: item.routeName,
                                    address: item.address,
                                    macAddress: item.macAddress,
                                    routeNameId: item.routeNameId
                                });
                            });
                            console.log("-----columnData1", columnData)
                            if (columnData.length != 0) {
                                this.setState({
                                    columnData: columnData,
                                    tableLoading: false,
                                    tableLoading1: true,
                                    dataLength: columnData.length,
                                    routeName: columnData[0].routeName
                                })
                                for (let i = 0; i < this.state.columnData.length; i++) {
                                    this.state.columnData[i].routeNum = i + 1;
                                }
                                console.log("-----columnData2", this.state.columnData)
                                updatePatrolRouteApi(this.state.columnData).then(res => { })
                            } else {
                                this.setState({
                                    columnData: columnData,
                                    tableLoading: false,
                                    tableLoading1: true,
                                    dataLength: columnData.length,
                                    routeName: this.state.routeName
                                })
                            }

                        })
                    message.success("删除成功")
                }
            })
    }
    //删除单个巡更点、保存线路顺序等刷新
    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = []
        getMultiroutepatrolAddressByRouteIdApi(parseInt(sessionStorage.getItem("departmentId")), this.state.routeNameIdByAdd)
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        checkPointId: item.checkPointId,
                        routeName: item.routeName,
                        address: item.address,
                        macAddress: item.macAddress,
                        routeNameId: item.routeNameId
                    });
                });
                console.log("-----columnData1", columnData)
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                    tableLoading1: true,
                    dataLength: columnData.length,
                    routeName: columnData[0].routeName
                })
            })
    }
    //删除整条路线刷新数据
    refreshData2() {
        getMultiroutepatrolRouteApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                if (res.data.length != 0) {
                    let routeName = res.data[0].routeName
                    let routeNameId = res.data[0].id
                    this.setState({
                        patrolRoute: res.data,
                        routeName: routeName,
                        routeNameId: routeNameId
                    })
                    let columnData = []
                    getMultiroutepatrolAddressByRouteIdApi(parseInt(sessionStorage.getItem("departmentId")), routeNameId)
                        .then((res) => {
                            res.data.forEach((item, index) => {
                                columnData.push({
                                    key: index + 1,
                                    id: item.id,
                                    checkPointId: item.checkPointId,
                                    address: item.address,
                                    macAddress: item.macAddress,
                                    routeNameId: item.routeNameId
                                });
                            });
                            this.setState({
                                columnData: columnData,
                                tableLoading: false,
                                tableLoading1: true,
                                dataLength: columnData.length,
                                addPatrolRouteVisible: false,
                                confirmLoading: false,
                            })
                        })
                } else {
                    this.setState({
                        patrolRoute: [],
                        routeName: "巡更路线",
                        columnData: [],
                        dataLength: 0,
                        confirmLoading: false
                    })
                }
            })
    }

    saveHandleClick() {
        this.setState({
            confirmLoading: true
        });
        for (let i = 0; i < this.state.columnData.length; i++) {
            this.state.columnData[i].routeNum = i + 1;
        }
        updatePatrolRouteApi(this.state.columnData)
            .then((res) => {
                if (res.data == "success") {
                    this.setState({
                        confirmLoading: false,
                        addPatrolRouteVisible: false
                    });
                    this.setState({
                        routeNameIdByAdd: this.state.columnData[0].routeNameId
                    })
                    message.success("保存成功!");
                    this.refreshData();
                } else if (res.data == "fail") {
                    this.setState({
                        alertVisible: true,
                        confirmLoading: false,
                        addPatrolRouteVisible: false,
                        msg: "保存失败,请检查信息或稍后再试!"
                    });
                    message.error("保存失败!");
                }
            })
            .catch((e) => {
                if (e.response) {
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false, msg: "" });
    }
    components = {
        body: {
            row: DragableBodyRow
        }
    }
    moveRow = (dragIndex, hoverIndex) => {
        const { columnData } = this.state;
        const dragRow = columnData[dragIndex];
        this.setState(
            update(this.state, {
                columnData: {
                    $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]]
                }
            })
        );
    }

    moveRow1 = (dragIndex, hoverIndex) => {
        const { columnData } = this.state;
        console.log("moveRow1------------------------------")
        const dragRow = columnData[dragIndex];
        this.setState(
            update(this.state, {
                columnData: {
                    $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]]
                }
            })
        );
        this.setState({
            addPatrolRouteVisible: false
        })
    }

    addPatrolRoute = () => {
        this.setState({
            addPatrolRouteVisible: true
        })
    }
    handleChange = (value, event) => {
        let columnData = []
        let routeNameId = `${value}`
        let routeName = event.props.children
        if (routeNameId == 'undefined') {
            this.setState({
                tableLoading1: false,
                addPatrolRouteVisible: false
            })
        }
        else {
            //根据Id获取对应的线路名
            getMultiroutepatrolAddressByRouteIdApi(parseInt(sessionStorage.getItem("departmentId")), routeNameId)
                .then((res) => {
                    res.data.forEach((item, index) => {
                        columnData.push({
                            key: index + 1,
                            id: item.id,
                            checkPointId: item.checkPointId,
                            address: item.address,
                            macAddress: item.macAddress,
                            routeNameId: item.routeNameId
                        });
                    });
                    this.setState({
                        columnData: columnData,
                        tableLoading: false,
                        tableLoading1: true,
                        dataLength: columnData.length,
                        addPatrolRouteVisible: false,
                        routeName: routeName,
                        routeNameId: routeNameId
                    })
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });

        }
    }
    updateRouteName = () => {
        this.setState({
            updateVisible: true,
            addPatrolRouteVisible: false
        })
    }
    handleUpdateCancel = () => {
        this.setState({
            updateVisible: false,
            addPatrolRouteVisible: false,
            msg: "",
            alertVisible: false
        })
    }
    //子组件调用父组件方法刷新数据
    getMultiPatrolRouteNames = (data) => {
        this.setState({
            patrolRoute: data,
            addPatrolRouteVisible: false
        });
    }
    handleUpdateClick = (e) => {
        this.setState({
            confirmLoading: true,
        });
        let val = this.refs.updatePatrolRouteNameValue;
        val.validateFields((err, values) => {
            if (!err) {
                console.log(values)
                updateRouteNameApi(parseInt(sessionStorage.getItem("departmentId")), values.routeName, this.state.routeNameId).then((res) => {
                    console.log(res.data)
                    if (res.data == "success") {
                        this.setState({
                            confirmLoading: false,
                            updateVisible: false,
                        });
                        message.success("修改成功")
                        getMultiroutepatrolRouteApi(parseInt(sessionStorage.getItem("departmentId"))).then((res) => {
                            this.setState({
                                patrolRoute: res.data,
                                routeName: values.routeName
                            });
                        })
                    } else if (res.data == "fail1") {
                        //路线名重复
                        this.setState({
                            confirmLoading: false,
                            alertVisible: true,
                            msg: "巡更路线名已存在，请重新修改!"
                        });

                    } else {
                        this.setState({
                            confirmLoading: false,
                            updateVisible: false,
                        });
                        message.success("修改失败")
                    }
                })

            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        })
    }

    //新增检查点
    showAddModal() {
        this.setState({
            addVisible: true,
        });
    }

    handleAddCancel = () => {
        let val = this.refs.addAddressFormValue;
        this.setState({
            alertVisible: false,
            msg: "",
            addVisible: false,
            confirmLoading: false,
            addPatrolRouteVisible: false,
        });
    }
    deleteRoute = () => {
        deleteRouteByRouteIdApi(parseInt(sessionStorage.getItem("departmentId")), parseInt(this.state.routeNameId)).then((res) => {
            console.log(res)
            if (res.data == "success") {
                message.success("删除成功!");
                this.refreshData2()
            } else if (res.data == "fail") {
                message.error("删除失败!");
            }
        })
    }

    addHandleClick() {
        this.setState({
            confirmLoading: true,
            addPatrolRouteVisible: false,
        });
        let val = this.refs.addAddressFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                addOneMultiroutepatrolAddressApi(values.routeNameId, values.addressIdAndChecPointId, parseInt(sessionStorage.getItem("departmentId")))
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.setState({
                                routeNameIdByAdd: values.routeNameId
                            })
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "repeat") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "巡更地址名称已存在，请更换!"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }
    render() {
        const patrolRouteOption = this.state.patrolRoute.map(v => {
            return (
                <Option value={v.id} key={v.id}>{v.routeName}</Option>
            );
        });
        if (this.state.routeName == "")
            return (
                <div>
                    <Skeleton loading={this.state.confirmLoading} active>
                        <Button type="primary" style={{ marginLeft: 15 }} size="large">
                            <Icon type="plus" theme="outlined" />新增巡更路线
                        </Button>
                        <Button type="primary" style={{ marginLeft: 15 }} size="large">
                            <Icon type="save" theme="outlined" />保存路线顺序
                        </Button>
                        <Button type="primary" style={{ marginLeft: 15 }} size="large">
                            <Icon type="save" theme="outlined" />修改当前路线名
                        </Button>
                        <Select
                            size="large"
                            placeholder="巡更路线"
                            style={{ width: 120, marginLeft: 15 }}
                        >
                        </Select>
                        <Table
                            columns={this.columns}
                            components={this.components}
                            locale={{ emptyText: '暂无数据' }}
                        ></Table>
                    </Skeleton>
                </div>
            )

        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" style={{ marginLeft: 15 }} onClick={this.addPatrolRoute.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />分配巡更路线
                    </Button>
                    <Select
                        size="large"
                        placeholder="巡更路线"
                        style={{ width: 200, marginLeft: 15 }}
                        onChange={this.handleChange}
                        defaultValue={this.state.routeName}
                        value={this.state.routeName}
                        disabled={this.state.patrolRoute.length == 0}
                    >
                        {patrolRouteOption}
                    </Select>
                    <AddPatrolRoute visible={this.state.addPatrolRouteVisible} getMultiPatrolRouteNames={this.getMultiPatrolRouteNames} />
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large"
                        style={{ marginLeft: 15 }} disabled={this.state.patrolRoute.length == 0}>
                        <Icon type="plus" theme="outlined" />新增检查点
                    </Button>
                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"新增巡更点地址"}
                                visible={this.state.addVisible}
                                onCancel={this.handleAddCancel}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.addHandleClick.bind(this)}>提交</Button>
                                ]}
                            >
                                <AddAddressForm ref="addAddressFormValue" />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    <Button type="primary" style={{ marginLeft: 15 }} onClick={this.updateRouteName.bind(this)}
                        disabled={this.state.patrolRoute.length == 0} size="large">
                        <Icon type="edit" theme="outlined" />修改当前路线名
                    </Button>
                    <Modal
                        destroyOnClose={true}
                        title={"修改当前路线名"}
                        visible={this.state.updateVisible}
                        onCancel={this.handleUpdateCancel.bind(this)}
                        width={'500px'}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large" onClick={this.handleUpdateClick.bind(this)}
                                loading={this.state.confirmLoading}>提交</Button>
                        ]}
                    >
                        <UpdatePatrolRouteName ref="updatePatrolRouteNameValue"
                            routeName={this.state.routeName} />
                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                    <Button type="primary" style={{ marginLeft: 15 }} onClick={this.deleteRoute.bind(this)}
                        disabled={this.state.patrolRoute.length == 0} size="large">
                        <Icon type="delete" theme="outlined" />删除当前路线
                    </Button>
                    <Button type="primary" style={{ marginLeft: 15 }} onClick={this.saveHandleClick.bind(this)} size="large"
                        disabled={this.state.patrolRoute.length == 0}>
                        <Icon type="save" theme="outlined" />保存路线顺序
                    </Button>
                </div>
                {this.state.tableLoading1 == true ?
                    <Table
                        dataSource={this.state.columnData}
                        columns={this.columns}
                        components={this.components}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onRow={(record, index) => ({
                            index,
                            moveRow: this.moveRow1
                        })}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            hideOnSinglePage: true,
                            total: this.state.dataLength, //数据总数量
                            defaultPageSize: this.state.dataLength, //默认显示几条一页
                            pageSize: this.state.dataLength,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            }
                        }}
                    ></Table>
                    : <Table
                        columns={this.columns}
                        components={this.components}
                        locale={{ emptyText: '暂无数据' }}
                    ></Table>
                }
            </div>
        )
    }
}
//旧版单路线巡更
// class SchoolPatrolRouteManager extends Component {
//     constructor(props) {
//         super(props);
//         this.columns = [
//             {
//                 title: "巡更次序",
//                 dataIndex: "key",
//                 key: "key"
//             },
//             {
//                 title: "地址",
//                 dataIndex: "address",
//                 key: "address"
//             }
//         ];

//         this.state = {
//             alertVisible: false,
//             confirmLoading: false,
//             msg: "", //提交失败时的提示语
//             tableLoading: true,
//             dataLength: 0
//         };

//     }

//     componentDidMount() {
//         this.refreshData();
//     }

//     refreshData() {
//         this.setState({
//             tableLoading: true
//         });
//         let columnData = [];
//         patrolRouteBySchoolApi(parseInt(sessionStorage.getItem("departmentId")))
//             .then((res) => {
//                 res.data.forEach((item, index) => {
//                     //console.log("getAllUser", item);
//                     columnData.push({
//                         key: index + 1,
//                         id: item.id,
//                         checkPointId: item.checkPointId,
//                         address: item.address,
//                         macAddress: item.macAddress
//                     });
//                 });
//                 this.setState({
//                     columnData: columnData,
//                     tableLoading: false,
//                     dataLength: columnData.length
//                 });
//                 //console.log(this.state)
//             })
//             .catch((e) => {
//                 if (e.response) {
//                     //请求已发出，服务器返回状态码不是2xx。
//                     console.info(e.response.data)
//                     console.info(e.response.status)
//                     console.info(e.response.headers)
//                 } else if (e.request) {
//                     // 请求已发出，但没有收到响应
//                     // e.request 在浏览器里是一个XMLHttpRequest实例，
//                     // 在node中是一个http.ClientRequest实例
//                     console.info(e.request)
//                 } else {
//                     //发送请求时异常，捕捉到错误
//                     console.info('error', e.message)
//                 }
//                 console.info(e.config)
//             });
//     }


//     saveHandleClick() {
//         this.setState({
//             confirmLoading: true
//         });
//         for (let i = 0; i < this.state.columnData.length; i++) {
//             this.state.columnData[i].routeNum = i + 1;
//         }
//         updatePatrolRouteApi(this.state.columnData)
//             .then((res) => {
//                 if (res.data == "success") {
//                     this.setState({
//                         confirmLoading: false
//                     });
//                     message.success("保存成功!");
//                     this.refreshData();
//                 } else if (res.data == "fail") {
//                     this.setState({
//                         alertVisible: true,
//                         confirmLoading: false,
//                         msg: "保存失败,请检查信息或稍后再试!"
//                     });
//                 }
//             })
//             .catch((e) => {
//                 if (e.response) {
//                     //请求已发出，服务器返回状态码不是2xx。
//                     console.info(e.response.data)
//                     console.info(e.response.status)
//                     console.info(e.response.headers)
//                 } else if (e.request) {
//                     // 请求已发出，但没有收到响应
//                     // e.request 在浏览器里是一个XMLHttpRequest实例，
//                     // 在node中是一个http.ClientRequest实例
//                     console.info(e.request)
//                 } else {
//                     //发送请求时异常，捕捉到错误
//                     console.info('error', e.message)
//                 }
//                 console.info(e.config)
//             });
//     }

//     //关闭 alert 的提示
//     handleClose() {
//         this.setState({ alertVisible: false });
//     }

//     components = {
//         body: {
//             row: DragableBodyRow
//         }
//     }

//     moveRow = (dragIndex, hoverIndex) => {
//         const { columnData } = this.state;
//         const dragRow = columnData[dragIndex];
//         //console.log(dragIndex, hoverIndex);
//         this.setState(
//             update(this.state, {
//                 columnData: {
//                     $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]]
//                 }
//             })
//         );
//         //console.log(this.state.data);
//     }

//     render() {
//         return (
//             <div>
//                 <div style={{ marginBottom: 16 }}>
//                     {
//                         this.state.alertVisible ?
//                             (
//                                 <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
//                             ) : null
//                     }
//                     <Button type="primary" onClick={this.saveHandleClick.bind(this)} size="large">
//                         <Icon type="save" theme="outlined" />保存路线顺序
//                     </Button>
//                 </div>
//                 <Table
//                     dataSource={this.state.columnData}
//                     columns={this.columns}
//                     components={this.components}
//                     loading={this.state.tableLoading}
//                     locale={{ emptyText: '暂无数据' }}
//                     onRow={(record, index) => ({
//                         index,
//                         moveRow: this.moveRow
//                     })}
//                     rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
//                     pagination={{  //分页
//                         hideOnSinglePage: true,
//                         total: this.state.dataLength, //数据总数量
//                         defaultPageSize: this.state.dataLength, //默认显示几条一页
//                         pageSize: this.state.dataLength,
//                         showTotal: function (total) {  //设置显示一共几条数据
//                             return '共 ' + total + ' 条数据';
//                         }
//                     }} />
//             </div>
//         )
//     }
// }
// class SchoolPatrolRouteManager extends Component {
//     constructor(props) {
//         super(props);
//         this.columns = [
//             {
//                 title: "巡更次序",
//                 dataIndex: "key",
//                 key: "key"
//             },
//             {
//                 title: "地址",
//                 dataIndex: "address",
//                 key: "address"
//             }
//         ];

//         this.state = {
//             alertVisible: false,
//             confirmLoading: false,
//             msg: "", //提交失败时的提示语
//             tableLoading: true,
//             dataLength: 0
//         };

//     }

//     componentDidMount() {
//         this.refreshData();
//     }

//     refreshData() {
//         this.setState({
//             tableLoading: true
//         });
//         let columnData = [];
//         patrolRouteBySchoolApi(parseInt(sessionStorage.getItem("departmentId")))
//             .then((res) => {
//                 res.data.forEach((item, index) => {
//                     //console.log("getAllUser", item);
//                     columnData.push({
//                         key: index + 1,
//                         id: item.id,
//                         checkPointId: item.checkPointId,
//                         address: item.address,
//                         macAddress: item.macAddress
//                     });
//                 });
//                 this.setState({
//                     columnData: columnData,
//                     tableLoading: false,
//                     dataLength: columnData.length
//                 });
//                 //console.log(this.state)
//             })
//             .catch((e) => {
//                 if (e.response) {
//                     //请求已发出，服务器返回状态码不是2xx。
//                     console.info(e.response.data)
//                     console.info(e.response.status)
//                     console.info(e.response.headers)
//                 } else if (e.request) {
//                     // 请求已发出，但没有收到响应
//                     // e.request 在浏览器里是一个XMLHttpRequest实例，
//                     // 在node中是一个http.ClientRequest实例
//                     console.info(e.request)
//                 } else {
//                     //发送请求时异常，捕捉到错误
//                     console.info('error', e.message)
//                 }
//                 console.info(e.config)
//             });
//     }


//     saveHandleClick() {
//         this.setState({
//             confirmLoading: true
//         });
//         for (let i = 0; i < this.state.columnData.length; i++) {
//             this.state.columnData[i].routeNum = i + 1;
//         }

//         if(this.state.columnData.length == 0){
//             message.error("请给路线分配巡检点!")
//         }
//         console.log("this.state.columData===========", this.state.columnData)
//         updatePatrolRouteApi(this.state.columnData)
//             .then((res) => {
//                 if (res.data == "success") {
//                     this.setState({
//                         confirmLoading: false
//                     });

//                         this.setState({
//                             routeNameIdByAdd: this.state.columnData[0].routeNameId
//                         })

//                     message.success("保存成功!");
//                     this.refreshData();
//                 } else if (res.data == "fail") {
//                     this.setState({
//                         alertVisible: true,
//                         confirmLoading: false,
//                         msg: "保存失败,请检查信息或稍后再试!"
//                     });
//                 }
//             })
//             .catch((e) => {
//                 if (e.response) {
//                     //请求已发出，服务器返回状态码不是2xx。
//                     console.info(e.response.data)
//                     console.info(e.response.status)
//                     console.info(e.response.headers)
//                 } else if (e.request) {
//                     // 请求已发出，但没有收到响应
//                     // e.request 在浏览器里是一个XMLHttpRequest实例，
//                     // 在node中是一个http.ClientRequest实例
//                     console.info(e.request)
//                 } else {
//                     //发送请求时异常，捕捉到错误
//                     console.info('error', e.message)
//                 }
//                 console.info(e.config)
//             });
//     }

//     //关闭 alert 的提示
//     handleClose() {
//         this.setState({ alertVisible: false });
//     }

//     components = {
//         body: {
//             row: DragableBodyRow
//         }
//     }

//     moveRow = (dragIndex, hoverIndex) => {
//         const { columnData } = this.state;
//         const dragRow = columnData[dragIndex];
//         //console.log(dragIndex, hoverIndex);
//         this.setState(
//             update(this.state, {
//                 columnData: {
//                     $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]]
//                 }
//             })
//         );
//         //console.log(this.state.data);
//     }

//     render() {
//         return (
//             <div>
//                 <div style={{ marginBottom: 16 }}>
//                     {
//                         this.state.alertVisible ?
//                             (
//                                 <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
//                             ) : null
//                     }
//                     <Button type="primary" onClick={this.saveHandleClick.bind(this)} size="large">
//                         <Icon type="save" theme="outlined" />保存路线顺序
//                     </Button>
//                 </div>
//                 <Table
//                     dataSource={this.state.columnData}
//                     columns={this.columns}
//                     components={this.components}
//                     loading={this.state.tableLoading}
//                     locale={{ emptyText: '暂无数据' }}
//                     onRow={(record, index) => ({
//                         index,
//                         moveRow: this.moveRow
//                     })}
//                     rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
//                     pagination={{  //分页
//                         hideOnSinglePage: true,
//                         total: this.state.dataLength, //数据总数量
//                         defaultPageSize: this.state.dataLength, //默认显示几条一页
//                         pageSize: this.state.dataLength,
//                         showTotal: function (total) {  //设置显示一共几条数据
//                             return '共 ' + total + ' 条数据';
//                         }
//                     }} />
//             </div>
//         )
//     }
// }
const PatrolRouteManager = DragDropContext(HTML5Backend)(SchoolPatrolRouteManager);
//修改线路名
class updatePatrolRouteName extends Component {
    constructor(props) {
        super(props);
        this.state = {
            routeName: props.routeName
        };
    }
    componentDidMount() {

    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        }
        return (
            <Form>
                <FormItem
                    label='巡更路线名'
                    {...formItemLayout}>
                    {getFieldDecorator("routeName", {
                        initialValue: this.state.routeName,
                        rules: [{
                            required: true,
                            message: "请输入巡更路线!"
                        }]
                    })(
                        <Input
                            size="large"
                            placeholder="巡更路线名"
                        />
                    )}
                </FormItem>
            </Form>
        )
    }
}
const UpdatePatrolRouteName = Form.create()(updatePatrolRouteName);
//新增线路
class addPatrolRoute extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: props.visible,
            currentStep: 0,
            confirmLoading: false,
            treeData: [],
            checkedKeys: [],
            addressIdList: [],
            patrolAddress: [],
            expandedKeys: [],
            alertVisible: false,
            msg: ""
        }
    }
    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
        });
    }
    componentDidMount() {
        let patrolAddress = []
        getMultiroutepatrolAddressBySchoolId(sessionStorage.getItem("departmentId")).then((res) => {
            console.log("address", res.data)
            res.data.patrolAddress.forEach((item, index) => {
                patrolAddress.push({
                    title: item.name,
                    key: item.addressId + "-" + item.checkPointId
                })
            })
            this.setState({
                patrolAddress: patrolAddress,
            })
        })
    }
    handleAddCancel() {
        getMultiroutepatrolRouteApi(parseInt(sessionStorage.getItem("departmentId"))).then((res) => {
            this.props.getMultiPatrolRouteNames(res.data);
            this.setState({
                visible: false,
                confirmLoading: false,
                addressIdList: [],
                currentStep: 0,
                alertVisible: false,
                msg: ""
            });
        })
    }
    onSubmit = (e) => {
        console.log("--------------------提交")
        this.setState({
            confirmLoading: true,
        })
        let schoolId = sessionStorage.getItem("departmentId");
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (this.state.addressIdList.length != 0) {
                    addMultiroutepatrolRoute(schoolId, values.routeName, this.state.addressIdList).then((res) => {
                        if (res.data == 'success') {
                            this.setState({
                                confirmLoading: false,
                                addressIdList: [],
                                currentStep: 1,
                                alertVisible: false,
                                msg: ""
                            })
                            message.success("提交成功!")
                        } else if (res.data == 'fail1') {
                            this.setState({
                                confirmLoading: false,
                                currentStep: 0,
                                alertVisible: true,
                                msg: "巡更路线名已存在，请重新输入!"
                            })
                        } else if (res.data == 'fail2') {
                            this.setState({
                                alertVisible: true,
                                msg: "巡更路线名已存在,请重新输入!"
                            })
                        }
                    })
                } else {
                    this.setState({
                        confirmLoading: true,
                        currentStep: 0,
                    })
                }
            }
        });
    }
    onCheck = (checkedKeys) => {
        let addressIdList = []
        checkedKeys.forEach((item, index) => {
            if (item != '0') {
                addressIdList.push(item)
            }
        })
        console.log('addressIdList', addressIdList);
        this.setState({
            addressIdList: addressIdList
        })
    }
    onExpand = () => {
        let patrolAddress = []
        getMultiroutepatrolAddressBySchoolId(sessionStorage.getItem("departmentId")).then((res) => {
            console.log("address", res.data)
            res.data.patrolAddress.forEach((item, index) => {
                patrolAddress.push({
                    title: item.name,
                    key: item.addressId + "-" + item.checkPointId
                })
            })
            this.setState({
                patrolAddress: patrolAddress
            })
        })
    }
    handleClose = () => {
        this.setState({
            alertVisible: false,
            msg: ""
        })
    }
    render() {
        const treeData = [
            {
                title: '所有巡更地址',
                key: '0',
                children: this.state.patrolAddress
            }
        ]
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        let stepPatrol = (
            <Steps
                current={this.state.currentStep}
                style={{
                    marginBottom: 30,
                }}>
                <Step title="分配巡更路线" description="请分配并提交" />
                <Step title="完成" />
            </Steps>
        );
        let drawerContent;
        let footerButton
        if (this.state.currentStep == 0) {
            drawerContent = (
                <Form onSubmit={this.next2}>
                    <FormItem
                        label='巡更路线名称'
                        {...formItemLayout}>
                        {getFieldDecorator("routeName", {
                            rules: [{
                                required: true,
                                message: "请定义巡更路线名称"
                            }]
                        })(
                            <Input
                                size="middle"
                                placeholder="巡更路线名称">
                            </Input>
                        )}
                    </FormItem>
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                    <Tree
                        checkable
                        selectable={true}
                        onExpand={this.onExpand}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.addressIdList}
                        treeData={treeData}
                    />
                </Form>
            )
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" loading={this.state.confirmLoading}
                        onClick={this.onSubmit.bind(this)}>提交</Button>
                </div>
            )
        } else if (this.state.currentStep == 1) {
            drawerContent = (
                <div>
                    <div style={{
                        textAlign: 'center',
                        width: '100%',
                        marginTop: 200,
                    }}>
                        <IconFont type='icon-locationiconsuccess' style={{ fontSize: '10em' }} />
                        <div style={{ fontSize: 20 }}>操作成功</div>
                    </div>
                </div>
            )
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                </div>
            )
        }
        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={800}
                title={'分配巡更路线'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    {stepPatrol}
                    {drawerContent}
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>

        )

    }
}
const AddPatrolRoute = Form.create()(addPatrolRoute);

//--------------------------------------------------------------
class SchoolInspectWithCheckpointManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addInspectItemPointRelationVisible: false, //控制新增用户模态框显示隐藏
            updateInspectItemPointRelationVisible: false,
            alertVisible: false,
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            // searchText: '',
            // allCategory: [],
            filteredInfo: null,
            data: [],

            fileList: [],
            uploading: false,
            addVisible: false,
        };


    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getInspectItemPointRelationBySchoolApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        address: item.address,
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
                this.child.refreshData();
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleDelete(id, school) {
        deleteInspectItemPointRelationApi(id, school)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //批量导入巡检地点与巡检项目关联
    batchImportInspectAddressAndInspectItem() {
        console.log("===============批量导入巡检地点与巡检项目关联====================")
        this.setState({
            addVisible: true,
            fileList: [],
        });
    }

    handleCancel = e => {
        this.setState({
            addVisible: false,
            fileList: [],
            uploading: false
        });
    };


    handleUpload = (e) => {
        let schoolId = sessionStorage.getItem("departmentId")
        const { fileList, buttonFlag } = this.state;
        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('upfile', file);
        });


        this.setState({
            uploading: true,
        });

        formData.append('schoolId', schoolId)
        batchImportInspectAddressAndInspectItemApi(formData).then((res) => {
            if (res.data == 'success') {
                this.setState({
                    fileList: [],
                    uploading: false,
                    addVisible: false
                });
                this.refreshData();
                message.success('导入成功！');
            }
            else {
                this.setState({
                    uploading: false,
                });
                //message.error(res.data);
                message.error("导入失败，请检查文件！")

            }
            this.setState({
                fileList: [],
                uploading: false,
            });
        })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            })

    }

    //点击表格中 添加 触发的操作
    showAddModal() {
        this.setState({
            addInspectItemPointRelationVisible: true,
        });
    }

    showUpdateModal(id) {
        this.setState({
            currentCheckpointId: id,
            updateInspectItemPointRelationVisible: true,

        });
        console.log('showUpdateModal=============', id);
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    //关闭模态框
    handleAddCancel() {
        this.setState({
            alertVisible: false,
            addInspectItemPointRelationVisible: false
        });
    }

    handleUpdateCancel() {
        this.setState({
            alertVisible: false,
            updateInspectItemPointRelationVisible: false
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
        });
    }


    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    onRef = (ref) => {
        this.child = ref
    }


    render() {
        // let { filteredInfo } = this.state;
        // filteredInfo = filteredInfo || {};

        const { uploading, fileList } = this.state;
        const props = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: file => {

                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));

                return false;
            },
            fileList,
        }

        this.columns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "排查点地址",
                dataIndex: "address",
                key: "address",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.address.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a href="javascript:;" onClick={this.showUpdateModal.bind(this, record.id)}>修改</a>
                        <Divider type="vertical" />
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDelete(record.id,
                                parseInt(sessionStorage.getItem("departmentId")))}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }
        ];
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增关联
                    </Button>

                    <Button type="primary" onClick={() => this.batchImportInspectAddressAndInspectItem()} size="large" style={{ marginLeft: '20px' }}>
                        <Icon type="plus" />批量导入
                    </Button>

                    <Button href={wangGeGuiHuaUploadTemplateUrl} style={{ marginLeft: 15 }} size="large"><Icon type="download" />下载网格规划导入模板</Button>

                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"导入关联信息"}
                                visible={this.state.addVisible}
                                onCancel={this.handleCancel}
                                closable
                                maskClosable={false}
                                footer={[]}
                                centered={true}
                                style={{ marginLeft: 15 }}
                            >
                                <Spin tip="导入数据时间较长，请耐心等待！" spinning={this.state.uploading} size="large">
                                    <Upload {...props}>
                                        <Button >
                                            <Icon type="upload" />选择文件
                                        </Button>
                                    </Upload>

                                    <Button
                                        type="primary"
                                        onClick={this.handleUpload}
                                        disabled={fileList.length === 0}
                                        loading={uploading}
                                        style={{ marginTop: 16 }}
                                    >
                                        {uploading ? '正在上传' : '开始上传'}
                                    </Button>
                                </Spin>
                            </Modal>) : null
                    }

                    {/* <Button style={{ marginLeft: '20px' }} onClick={this.clearAll}>清除筛选</Button> */}
                    <AddInspectItemPointRelationForm
                        visible={this.state.addInspectItemPointRelationVisible}
                        that={this} />
                    <UpdateInspectItemPointRelationForm
                        visible={this.state.updateInspectItemPointRelationVisible}
                        currentCheckpointId={this.state.currentCheckpointId}
                        that={this} />
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={this.columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    expandedRowRender={(record) => {
                        return (
                            <InspectItemPointRelationInnerTable
                                //wrappedComponentRef={(inst) => this.teammateTableFormRef = inst}
                                //ref="teammateTableRefresh"
                                onRef={this.onRef}
                                checkpointId={record.id}
                                that={this} />)
                    }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}

class AddInspectItemPointRelationForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: [],
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [], //以上为树结构的数据，表示category与item
            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语

            mockData: [], //穿梭框数据,表示地点数据
            targetKeys: [],

            visible: props.visible,
            that: props.that,
            currentStep: 0,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
            that: props.that,
        });
        if (props.visible) {
            this.refreshData();
        }
    }

    refreshData() {
        this.setState({
            confirmLoading: true,
        })
        let allCheckPoint = [];
        checkpointBySchoolAndTypeExceptExistApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log(item);
                    allCheckPoint.push({
                        key: item.id,
                        title: item.address,
                        chose: 0
                    });
                });
                this.setState({
                    mockData: allCheckPoint,
                    targetKeys: [],
                    confirmLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getInspectItemFromManualWithTree(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let treeData = [];
                res.data.forEach((item, index) => {
                    let category = {
                        title: item.categoryName,
                        key: item.categoryId,
                        children: []
                    }
                    item.items.forEach((item2, index2) => {
                        category.children.push({
                            title: item2,
                            key: item.categoryId + '-' + item2,
                        })
                    })
                    treeData.push(category);
                });
                this.setState({
                    treeData: treeData,
                    checkedKeys: [],
                    expandedKeys: [],
                    autoExpandParent: true,
                    confirmLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //添加点关联
    handleAddClick() {
        this.setState({
            confirmLoading: true
        });
        let checkedKeysValues = [];
        this.state.checkedKeys.forEach((value, index) => {
            let temp = value.split('-');
            if (temp.length == 2) {
                checkedKeysValues.push(value);
            }
        });
        console.log('checkedKeysValues项目', checkedKeysValues);
        console.log('targetKeys地点', this.state.targetKeys);
        addInspectItemPointRelationApi(
            this.state.targetKeys, checkedKeysValues, parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                if (res.data == "success") {
                    message.success("更新成功!");
                    this.setState({
                        confirmLoading: false
                    });
                    this.next();
                    //this.state.that.handleAddCancel();
                    this.state.that.refreshData();
                } else if (res.data == "fail") {
                    this.setState({
                        alertVisible: true,
                        confirmLoading: false,
                        msg: "修改失败,请检查信息或稍后再试!"
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }

    onCheck = (checkedKeys) => {
        //console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    }

    onSelect = (selectedKeys, info) => {
        //console.log('onSelect', info);
        //this.setState({ selectedKeys });
    }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })


    handleMockChange = (targetKeys) => {
        this.setState({ targetKeys });
    }

    mockReload = () => {
        this.setState({ targetKeys: [] });
    }

    renderFooter = () => (
        <Button
            size="small"
            style={{ float: 'right', margin: 5 }}
            onClick={this.mockReload}>重置</Button>
    )

    next() {
        if (this.state.targetKeys.length == 0) {
            message.error("请选择地点!");
        } else {
            const currentStep = this.state.currentStep + 1;
            this.setState({ currentStep: currentStep });
        }

    }

    prev() {
        const currentStep = this.state.currentStep - 1;
        this.setState({
            currentStep: currentStep,
            checkedKeys: [],
        });
    }

    continueAdd() {
        this.setState({
            targetKeys: [],
            checkedKeys: [],
            currentStep: 0,
        })
    }

    handleAddCancel() {
        this.setState({
            currentStep: 0,
            targetKeys: [],
            checkedKeys: [],
        });
        //父类关闭
        this.state.that.handleAddCancel();
    }

    render() {
        //console.log('treeData', this.state.treeData);
        let drawerContent;
        if (this.state.currentStep == 0) {
            drawerContent = (
                <div>
                    <Steps current={this.state.currentStep}>
                        <Step title="选择地点" description="可多选" />
                        <Step title="选择项目" description="可多选" />
                        <Step title="完成" />
                    </Steps>
                    <Transfer
                        style={{
                            marginTop: 30,
                            textAlign: 'center',
                        }}
                        dataSource={this.state.mockData}
                        showSearch
                        listStyle={{
                            width: 300,
                            height: 500,
                            textAlign: 'left',
                        }}
                        titles={['选项', '已选择']}
                        operations={['添加', '取消']}
                        targetKeys={this.state.targetKeys}
                        onChange={this.handleMockChange}
                        render={item => `${item.title}`}
                        footer={this.renderFooter}
                    />
                </div>
            )
        } else if (this.state.currentStep == 1) {
            drawerContent = (
                <div>
                    <Steps
                        current={this.state.currentStep}
                        style={{
                            marginBottom: 30,
                        }}>
                        <Step title="选择地点" description="可多选" />
                        <Step title="选择项目" description="可多选" />
                        <Step title="完成" />
                    </Steps>
                    <Tree
                        checkable
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                    >
                        {this.renderTreeNodes(this.state.treeData)}
                    </Tree>
                </div>
            )
        } else if (this.state.currentStep == 2) {
            drawerContent = (
                <div>
                    <Steps current={this.state.currentStep}>
                        <Step title="选择地点" description="可多选" />
                        <Step title="选择项目" description="可多选" />
                        <Step title="完成" />
                    </Steps>
                    <div style={{
                        textAlign: 'center',
                        width: '100%',
                        marginTop: 200,
                    }}>
                        <IconFont type='icon-locationiconsuccess' style={{ fontSize: '10em' }} />
                        <div style={{ fontSize: 20 }}>操作成功</div>
                    </div>
                </div>
            )
        }

        let footerButton;
        if (this.state.currentStep == 0) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large"
                        onClick={() => this.next()}>下一步</Button>
                </div>
            )
        } else if (this.state.currentStep == 1) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" onClick={() => this.prev()}
                        style={{ marginRight: 20 }} >上一步</Button>
                    <Button type="primary" size="large" loading={this.state.confirmLoading}
                        onClick={this.handleAddClick.bind(this)}>提交</Button>
                </div>
            )
        } else if (this.state.currentStep == 2) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large"
                        onClick={() => this.continueAdd()}>继续添加</Button>
                </div>
            )
        }

        return (
            <Drawer
                bodyStyle={{ paddingBottom: 80 }}
                width={800}
                title={'新增关联'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    {drawerContent}
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        )
    }
}

class UpdateInspectItemPointRelationForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: [],
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [], //以上为树结构的数据，表示category与item
            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语

            visible: props.visible,
            that: props.that,
            currentCheckpointId: props.currentCheckpointId,
        };
        //console.log('currentCheckpointId', props.currentCheckpointId)
    }

    // componentDidMount() {
    //     this.refreshData();
    // }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
            that: props.that,
            currentCheckpointId: props.currentCheckpointId,
        });
        //console.log('visible', props.visible)
        if (props.visible) {
            this.refreshData(props.currentCheckpointId);
        }
    }

    refreshData(currentCheckpointId) {
        this.setState({
            confirmLoading: true,
        })
        //console.log('currentCheckpointId', this.state.currentCheckpointId)
        getInspectItemCheckpointRelationByCheckpointIdWithTree(
            currentCheckpointId, parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let treeData = [];
                let checkedKeys = [];
                res.data.forEach((item, index) => {
                    let category = {
                        title: item.categoryName,
                        key: item.categoryId,
                        children: []
                    }
                    item.items.forEach((item2, index2) => {
                        category.children.push({
                            title: item2.checkItem,
                            key: item.categoryId + "-" + item2.checkItem
                        });
                        if (item2.used == 1) {
                            checkedKeys.push(item.categoryId + "-" + item2.checkItem)
                        }
                    })
                    treeData.push(category);
                });
                this.setState({
                    treeData: treeData,
                    checkedKeys: checkedKeys,
                    expandedKeys: checkedKeys,
                    autoExpandParent: true,
                    confirmLoading: false,
                });
                console.log('treeData', treeData)
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleUpdateClick() {
        this.setState({
            confirmLoading: true
        });
        let checkedKeysValues = [];
        this.state.checkedKeys.forEach((value, index) => {
            let temp = value.split('-');
            if (temp.length == 2) {
                checkedKeysValues.push(value);
            }
        });
        updateInspectItemCheckpointRelation(this.state.currentCheckpointId,
            checkedKeysValues, parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                if (res.data == "success") {
                    message.success("更新成功!");
                    this.setState({
                        confirmLoading: false
                    });
                    this.state.that.handleUpdateCancel();
                    this.state.that.refreshData();
                } else if (res.data == "fail") {
                    this.setState({
                        alertVisible: true,
                        confirmLoading: false,
                        msg: "修改失败,请检查信息或稍后再试!"
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }

    onCheck = (checkedKeys) => {
        //console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    }

    onSelect = (selectedKeys, info) => {
        //console.log('onSelect', info);
        //this.setState({ selectedKeys });
    }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })

    render() {

        return (
            <Drawer
                bodyStyle={{ paddingBottom: 80 }}
                width={600}
                title={'更新排查点配置'}
                visible={this.state.visible}
                onClose={this.state.that.handleUpdateCancel.bind(this.state.that)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    <Tree
                        checkable
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                    >
                        {this.renderTreeNodes(this.state.treeData)}
                    </Tree>
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    <Button size="large" onClick={this.state.that.handleUpdateCancel.bind(this.state.that)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" loading={this.state.confirmLoading}
                        onClick={this.handleUpdateClick.bind(this)}>更新</Button>
                </div>
            </Drawer>
        )
    }

}

class InspectItemPointRelationInnerTable extends Component {
    constructor(props) {
        super(props);
        const innerColumns = [{
            title: '巡检类别',
            dataIndex: 'categoryName',
            key: 'categoryName',
            className: 'tableHeadColumn',
            width: '30%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa' }} />,
            onFilter: (value, record) => record.categoryName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            },
            render: (text, record, index) => {
                const obj = {
                    children: text,
                    props: {},
                };
                obj.props.rowSpan = record.rowSpan;

                return obj;
            },
        }, {
            title: '排查项目',
            dataIndex: 'item',
            key: 'item',
            width: '50%',
        }, {
            title: "操作详情",
            key: "action",
            width: '20%',
            render: (text, record) => (
                <span>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDelete(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            checkpointId: props.checkpointId,
            innerData: [],
            innerColumns: innerColumns,
            that: props.that
        };
    }

    componentDidMount() {
        this.refreshData();
        this.props.onRef(this);
    }

    componentWillReceiveProps(props) {
        this.setState({
            checkpointId: props.checkpointId,
            that: props.that,
        });
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        getInspectItemPointRelationDetailByCheckpointIdApi(
            this.state.checkpointId, parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    innerData.push({
                        id: item.id,
                        categoryId: item.categoryId,
                        categoryName: item.category,
                        item: item.item,
                        rowSpan: 0
                    })
                })
                //为了表格的列合并
                let count = 1;
                for (let i = innerData.length - 1; i >= 0; i--) {
                    if (i == 0) {
                        innerData[i].rowSpan = count;
                        break;
                    }
                    if (innerData[i].categoryId == innerData[i - 1].categoryId) {
                        count++;
                    } else {
                        innerData[i].rowSpan = count;
                        count = 1;
                    }
                }
                //console.log(innerData)
                this.setState({
                    innerData: innerData,
                    tableLoading: false
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleDelete(id) {
        deleteInspectItemPointRelationByRelationIdApi(id)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                    this.state.that.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    render() {
        return (
            <Table
                columns={this.state.innerColumns}
                dataSource={this.state.innerData}
                pagination={false}
                size='small'
                loading={this.state.tableLoading}
                locale={{ emptyText: '暂无数据' }}
                bordered={true}
                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
            />
        )
    }


}

//--------------------------------------------------------------------
class SchoolPatrolPlanManager extends Component {
    constructor(props) {
        super(props);

        this.state = {
            updateVisible: false, //控制修改信息模态框显示隐藏
            addVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            planNum: 0,
            data: [],
            // searchText: '',
            filteredInfo: null,
            sortedInfo: null,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        patrolPlanBySchoolApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                //console.log(res);
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        timeStart: item.startTime,
                        timeEnd: item.endTime,
                        teamName: item.name,
                        teamId: item.classId,
                        classmates: item.matesAll,

                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        checkpointBySchoolAndTypeApi(parseInt(sessionStorage.getItem("departmentId")), 1)
            .then((res) => {
                //console.log(res.data);
                this.setState({
                    planNum: res.data.length
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleDelete(id, school) {
        deletePatrolPlanApi(id, school)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //点击表格中 修改 触发的操作
    showUpdateModal(id, school, timeStart, timeEnd, teamId) {
        
        this.setState({
            updateVisible: true,
            currentId: id,
            currentSchool: school,
            currentTimeStart: timeStart,
            currentTimeEnd: timeEnd,
            currentTeamId: teamId
        });
    }

    //修改巡逻计划 点击提交按钮后的操作
    updateHandleClick(id) {
        
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.updatePatrolPlanFormValue;
        val.validateFields((err, values) => {
            
            if (!err) {
                values.startTime = moment(values.startTime).format('HH:mm:ss');
                values.endTime = moment(values.endTime).format('HH:mm:ss');
                values.schoolId = parseInt(sessionStorage.getItem("departmentId"));
                //console.log(values);
                //console.log(id);
                // if (values.startTime >= values.endTime) {
                //     this.setState({
                //         alertVisible: true,
                //         updateVisible: true,
                //         confirmLoading: false,
                //         msg: "开始时间不可晚于结束时间!"
                //     });
                // } else {
                updatePatrolPlanApi(id, values)
                    .then((res) => {
                        if (res.data == "success") {
                            console.log('success');
                            this.setState({
                                updateVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            val.resetFields();
                        } else if (res.data == "fail") {
                            console.log('fail');
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        } else if (res.data == "timeout") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "此计划的工作时间超出班组的工作时间!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    showAddModal() {
        this.setState({
            addVisible: true
        });
    }

    //新增 点击提交按钮后的操作
    addHandleClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addPatrolPlanFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                values.schoolId = parseInt(sessionStorage.getItem("departmentId"));
                values.startTime = moment(values.startTime).format('HH:mm:ss');
                values.endTime = moment(values.endTime).format('HH:mm:ss');
                values.should = this.state.planNum;
                // //console.log(values);
                // if (values.startTime >= values.endTime) {
                //     this.setState({
                //         alertVisible: true,
                //         confirmLoading: false,
                //         msg: "巡更开始时间不可小于结束时间!"
                //     });
                // } else {
                addPatrolPlanApi(values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            val.resetFields();
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "提交失败!"
                            });
                        } else if (res.data == "timeout") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "此计划的工作时间超出班组的工作时间!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    //关闭模态框
    handleUpdateCancel() {
        let val = this.refs.updatePatrolPlanFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            updateVisible: false,
        });
    }

    //关闭模态框
    handleAddCancel() {
        let val = this.refs.addPatrolPlanFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addVisible: false
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        const columns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "开始时间",
                dataIndex: "timeStart",
                key: "timeStart",
                sorter: (a, b) => new Date('2018-1-1 ' + a.timeStart).getTime() - new Date('2018-1-1 ' + b.timeStart).getTime(),
                sortOrder: sortedInfo.columnKey === 'timeStart' && sortedInfo.order,
            },
            {
                title: "结束时间",
                dataIndex: "timeEnd",
                key: "timeEnd",
                sorter: (a, b) => new Date('2018-1-1 ' + a.timeEnd).getTime() - new Date('2018-1-1 ' + b.timeEnd).getTime(),
                sortOrder: sortedInfo.columnKey === 'timeEnd' && sortedInfo.order,
            },
            {
                title: "班次名称",
                dataIndex: "teamName",
                key: "teamName",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.teamName.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "成员",
                dataIndex: "classmates",
                key: "classmates",
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a href="javascript:;" onClick={this.showUpdateModal.bind(this,
                            record.id, parseInt(sessionStorage.getItem("departmentId")),
                            record.timeStart, record.timeEnd, record.teamId)}>修改</a>
                        <Divider type="vertical" />
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDelete(record.id, sessionStorage.getItem("departmentId"))}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }
        ];
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增计划
                    </Button>
                    <Button style={{ marginLeft: '20px' }} onClick={this.clearAll}>
                        <Icon type="delete" theme="outlined" />清除排序
                    </Button>
                    <Modal
                        destroyOnClose={true}
                        title={"修改巡更计划"}
                        visible={this.state.updateVisible}
                        onCancel={this.handleUpdateCancel.bind(this)}
                        width={'700px'}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                onClick={this.updateHandleClick.bind(this, this.state.currentId)}>提交</Button>
                        ]}
                    >
                        <UpdatePatrolPlanForm ref="updatePatrolPlanFormValue"
                            currentTimeStart={this.state.currentTimeStart} currentTimeEnd={this.state.currentTimeEnd}
                            currentTeamId={this.state.currentTeamId} />
                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                    <Modal
                        destroyOnClose={true}
                        title={"新增巡更计划"}
                        visible={this.state.addVisible}
                        onCancel={this.handleAddCancel.bind(this)}
                        width={'700px'}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                onClick={this.addHandleClick.bind(this)}>提交</Button>
                        ]}
                    >
                        <AddPatrolPlanForm ref="addPatrolPlanFormValue" />
                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}


class updatePatrolPlanForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentTimeStart: props.currentTimeStart,
            currentTimeEnd: props.currentTimeEnd,
            currentTeamId: props.currentTeamId,
            allTeamOptions: [],
        };
    }

    componentDidMount() {
        let allTeamOptions = [];
        teamOptionsBySchoolAndType(parseInt(sessionStorage.getItem("departmentId")), 1)
            .then((res) => {
                res.data.forEach((item, index) => {
                    allTeamOptions.push({
                        value: item.id,
                        text: item.name + '  |  负责人：' + item.realName + '  |  工作时间：' + item.startTime + '~' + item.endTime
                    });
                });

                this.setState({
                    allTeamOptions: allTeamOptions
                })
                console.log(allTeamOptions);
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    render() {
        
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        }

        const options = this.state.allTeamOptions.map((d, index) => <Option value={d.value} key={index}>{d.text}</Option>);
        //console.log(1, this.state.currentAddress);
        return (
            <Form>
                <FormItem
                    label='开始时间'
                    {...formItemLayout}>
                    {getFieldDecorator("startTime", {
                        initialValue: moment(this.state.currentTimeStart, 'HH:mm:ss'),
                        rules: [{ required: true, message: "请输入开始时间!" }]
                    })(
                        <TimePicker
                            size="large"
                            minuteStep={5}
                            secondStep={60}
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="开始时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='结束时间'
                    {...formItemLayout}>
                    {getFieldDecorator("endTime", {
                        initialValue: moment(this.state.currentTimeEnd, 'HH:mm:ss'),
                        rules: [{ required: true, message: "请输入结束时间!" }]
                    })(
                        <TimePicker
                            size="large"
                            minuteStep={5}
                            secondStep={60}
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="结束时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='可选班组'
                    {...formItemLayout}>
                    {getFieldDecorator("teamId", {
                        initialValue: this.state.currentTeamId,
                        rules: [{
                            required: true,
                            message: "请选择班组!"
                        }]
                    })(
                        <Select
                            size="large"
                            style={{ width: '500px' }}
                            placeholder="选择班组">
                            {options}
                        </Select>
                    )}
                </FormItem>

            </Form>
        );
    }
}
const UpdatePatrolPlanForm = Form.create()(updatePatrolPlanForm);


class addPatrolPlanForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            teamId: -1,
            allTeamOptions: []
        };
    }

    componentDidMount() {
        teamOptionsBySchoolAndType(parseInt(sessionStorage.getItem("departmentId")), 1)
            .then((res) => {
                let allTeamOptions = [];
                res.data.forEach((item, index) => {
                    allTeamOptions.push({
                        teamId: item.id,
                        text: item.name + '  |  负责人：' + item.realName + '  |  工作时间：' + item.startTime + '~' + item.endTime
                    })
                });
                let options = allTeamOptions.map((d, index) => <Option value={d.teamId} key={index}>{d.text}</Option>);
                this.setState({
                    allTeamOptions: options
                })
                //console.log(options);
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }


    selectOnChange = (value) => {
        console.log(value);
        this.setState({
            teamId: value
        })
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        //const allTeamOptions = this.state.allTeamOption.map((d, index) => <Option value={d.teamId} key={index}>{d.text}</Option>);
        //console.log(this.state.allTeamOption);
        return (
            <Form>
                <FormItem
                    label='开始时间'
                    {...formItemLayout}>
                    {getFieldDecorator("startTime", {
                        rules: [{ required: true, message: "请输入开始时间!" }]
                    })(
                        <TimePicker
                            size="large"
                            minuteStep={5}
                            secondStep={60}
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="开始时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='结束时间'
                    {...formItemLayout}>
                    {getFieldDecorator("endTime", {
                        rules: [{ required: true, message: "请输入结束时间!" }]
                    })(
                        <TimePicker
                            size="large"
                            minuteStep={5}
                            secondStep={60}
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="结束时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='可选班组'
                    {...formItemLayout}>
                    {getFieldDecorator("teamId", {
                        rules: [{
                            required: true,
                            message: "请选择班组!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="选择班组"
                            style={{ width: '500px' }}
                            onChange={this.selectOnChange}>
                            {this.state.allTeamOptions}
                        </Select>
                    )}
                </FormItem>
            </Form>
        );
    }
}
const AddPatrolPlanForm = Form.create()(addPatrolPlanForm);



class SchoolInspectPlanManager extends Component {
    constructor(props) {
        super(props);

        this.state = {
            addVisible: false,
            updateVisible: false,
            addFromHistoryVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            data: [],
            // searchText: ''
            fileList: [],
            uploading: false,
            addVisible1: false,
            teamTypeFilter: [
                { text: '巡更', value: 1 },
                { text: '巡检', value: 2 },
            ],
            
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        inspectPlanMakeClassBySchoolApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                var cata=[];
                res.data.forEach((item, index) => {
                    cata=item.category.split(",")
                    console.log("getAllUser", cata);
                    columnData.push({
                        key: index + 1,
                        teamId: item.classId,
                        teamName: item.name,
                        classmates: item.username,
                        categoryName: cata,
                        teamType:2
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                    alertVisible: false,
                });
                this.child.refreshData();
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    // handleDelete(id, school) {
    //     deleteInspectPlanApi(id, school)
    //         .then((res) => {
    //             if (res.data == "success") {
    //                 message.success("删除成功!");
    //                 this.refreshData();
    //             } else {
    //                 message.error('删除失败,请稍后再试!');
    //             }
    //         })
    //         .catch((e) => {
    //             if (e.response) {
    //                 //请求已发出，服务器返回状态码不是2xx。
    //                 console.info(e.response.data)
    //                 console.info(e.response.status)
    //                 console.info(e.response.headers)
    //             } else if (e.request) {
    //                 // 请求已发出，但没有收到响应
    //                 // e.request 在浏览器里是一个XMLHttpRequest实例，
    //                 // 在node中是一个http.ClientRequest实例
    //                 console.info(e.request)
    //             } else {
    //                 //发送请求时异常，捕捉到错误
    //                 console.info('error', e.message)
    //             }
    //             console.info(e.config)
    //         });
    // }



    //批量导入巡检计划
    batchImportInspectPlan() {
        console.log("===============批量导入巡检计划====================")
        this.setState({
            addVisible1: true,
            fileList: [],
        });
    }

    handleCancel = e => {
        this.setState({
            addVisible1: false,
            fileList: [],
            uploading: false
        });
    };


    handleUpload = (e) => {
        let schoolId = sessionStorage.getItem("departmentId")
        const { fileList, buttonFlag } = this.state;
        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('upfile', file);
        });


        this.setState({
            uploading: true,
        });

        formData.append('schoolId', schoolId)
        batchImportInspectPlanApi(formData).then((res) => {
            if (res.data == 'success') {
                this.setState({
                    fileList: [],
                    uploading: false,
                    addVisible1: false
                });
                this.refreshData();
                message.success('导入成功！');
            }
            else {
                this.setState({
                    uploading: false,
                });
                message.error(res.data);
                message.error("导入失败，请检查文件！")
            }
            this.setState({
                fileList: [],
                uploading: false,
            });
        })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            })

    }

    showAddModal() {
        this.setState({
            addVisible: true
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    //关闭模态框
    handleAddCancel() {
        this.setState({
            alertVisible: false,
            addVisible: false
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    onRef = (ref) => {
        this.child = ref
    }

    addFromHistoryDrawerOpen = () => {
        this.setState({
            addFromHistoryVisible: true
        });
    }

    addFromHistoryDrawerClose = () => {
        this.setState({
            alertVisible: false,
            addFromHistoryVisible: false
        });
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};


        const { uploading, fileList } = this.state;
        const props = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: file => {

                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));

                return false;
            },
            fileList,
        }

        const columns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "班次名称",
                dataIndex: "teamName",
                key: "teamName",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.teamName.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "成员",
                dataIndex: "classmates",
                key: "classmates",
            },
            {
                title: "班次类型",
                dataIndex: "teamType",
                key: "teamType",
                render: (text, record) => {
                    //console.log(record);
                    if (record.teamType == 2) {
                        
                        let tags = record.categoryName.map((row, index) => <Tag color={'#87d068'}>{row}</Tag>)
                        return (
                            <div>
                                <Tag color={'blue'}>{'巡检'}</Tag>
                                {tags}
                            </div>
                        );
                    }
    
                },
                filters: this.state.teamTypeFilter,
                filteredValue: filteredInfo.teamType || null,
                onFilter: (value, record) => record.teamType == value,
                filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            },
            // {
            //     title: "操作",
            //     key: "action",
            //     render: (text, record) => (
            //         <span>
            //             <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
            //                 onConfirm={() => this.handleDelete(record.id, sessionStorage.getItem("departmentId"))}>
            //                 <a href="#">删除</a>
            //             </Popconfirm>
            //         </span>
            //     )
            // }
        ];
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" />新增计划
                    </Button>

                    <Button type="primary" onClick={() => this.batchImportInspectPlan()} size="large" style={{ marginLeft: '20px' }}>
                        <Icon type="plus" />批量导入
                    </Button>



                    <Button href={inspectPlanUploadTemplateUrl} style={{ marginLeft: 15 }} size="large"><Icon type="download" />下载巡检计划导入模板</Button>

                    {
                        this.state.addVisible1 ? (
                            <Modal
                                title={"导入巡检计划信息"}
                                visible={this.state.addVisible1}
                                onCancel={this.handleCancel}
                                closable
                                maskClosable={false}
                                footer={[]}
                                centered={true}
                                style={{ marginLeft: 15 }}
                            >
                                <Spin tip="导入数据时间较长，请耐心等待！" spinning={this.state.uploading} size="large">
                                    <Upload {...props}>
                                        <Button >
                                            <Icon type="upload" />选择文件
                                        </Button>
                                    </Upload>

                                    <Button
                                        type="primary"
                                        onClick={this.handleUpload}
                                        disabled={fileList.length === 0}
                                        loading={uploading}
                                        style={{ marginTop: 16 }}
                                    >
                                        {uploading ? '正在上传' : '开始上传'}
                                    </Button>
                                </Spin>
                            </Modal>) : null
                    }



                    {/* <Button style={{ marginLeft: '20px' }} onClick={this.addFromHistoryDrawerOpen} size="large">
                        <Icon type="snippets" theme="outlined" />查看历史计划
                    </Button> */}
                    {
                        this.state.addVisible ?
                            <AddInspectPlanForm
                                visible={this.state.addVisible}
                                that={this} />:null
                    }

                    {/* <InspectPlanHistory
                        visible={this.state.addFromHistoryVisible}
                        that={this} /> */}
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    expandedRowRender={(record) => {
                        return (
                            <InspectPlanInnerTable
                                //wrappedComponentRef={(inst) => this.teammateTableFormRef = inst}
                                //ref="teammateTableRefresh"
                                onRef={this.onRef}
                                teamId={record.teamId}
                                teamName={record.teamName}
                                that={this} />)
                    }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}

class InspectPlanHistory extends Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: [],
            confirmLoading: false,
            submitLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            visible: props.visible,
            that: props.that,
            startDate: moment(moment().subtract(1, 'months').format('YYYY-MM-DD'), 'YYYY-MM-DD'),
            endDate: moment(moment().format('YYYY-MM-DD'), 'YYYY-MM-DD'),
            modalTreeData: [],
        };
        this.modalFormRef = React.createRef();
    }

    // componentDidMount() {
    //     this.refreshData();
    // }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
        });
        if (props.visible) {
            this.refreshData();
        }

    }

    refreshData() {
        this.setState({
            confirmLoading: true,
        });

        getInspectPlanHistoryApi(parseInt(sessionStorage.getItem("departmentId")),
            this.state.startDate.format('YYYY-MM-DD'), this.state.endDate.format('YYYY-MM-DD'))
            .then((res) => {
                let treeData = [];
                let expandedKeys = [];

                let symbolSet = new Set();

                res.data.data.forEach((classItem) => {
                    let classTemp = {
                        title: classItem.className,
                        key: classItem.classId,
                        children: []
                    }
                    let currentKey11 = classItem.classId + '-*-' + classItem.className;
                    expandedKeys.push(classItem.classId)

                    classItem.checkpoint.forEach((checkpointItem) => {
                        let currentKey22 = currentKey11 + '-*-' + checkpointItem.symbol + '-*-'
                            + checkpointItem.address + '-*-' + checkpointItem.cycle;
                        let checkpointTemp = {
                            title: checkpointItem.address +
                                '(' + checkpointItem.startDate + '~' + checkpointItem.endDate + '，每' + checkpointItem.cycle + ')',
                            key: checkpointItem.symbol,
                            children: []
                        }

                        symbolSet.add(checkpointItem.symbol)
                        let symbolIndex = symbolSet.size;

                        checkpointItem.detail.forEach((detailItem) => {
                            let currentKey33 = currentKey22 + '-*-' + detailItem.categoryId + '-*-' + detailItem.category;
                            let detailTemp = {
                                title: detailItem.category,
                                key: currentKey22 + '-*-' + detailItem.categoryId,
                                children: []
                            }

                            detailItem.item.forEach((currentItem) => {
                                detailTemp.children.push({
                                    title: currentItem.checkItem,
                                    key: currentKey33 + '-*-' + currentItem.inspectitempointrelationId + '-*-' + currentItem.checkItem
                                        + '-*-' + symbolIndex
                                })
                            })

                            checkpointTemp.children.push(detailTemp);
                        })

                        classTemp.children.push(checkpointTemp);

                    })
                    treeData.push(classTemp);
                });
                this.setState({
                    treeData: treeData,
                    checkedKeys: [],
                    expandedKeys: expandedKeys,
                    autoExpandParent: true,
                    confirmLoading: false,
                });
            }).catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }


    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleDrawerCancel() {
        this.setState({
            visible: false,
        });
        this.state.that.addFromHistoryDrawerClose();
    }

    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }

    onCheck = (checkedKeys) => {
        console.log('onCheck', checkedKeys);
        let modalTreeData = [];
        if (checkedKeys.length > 0) {
            let tempArr = checkedKeys.filter((value) => {
                return value.split('-*-').length === 10;
            });
            tempArr.sort();
            modalTreeData = tempArr.map((value) => {
                let wordsArr = value.split('-*-');
                return {
                    title: wordsArr[1] + ' | ' + wordsArr[3] + ' | 每' + wordsArr[4] + ' | '
                        + wordsArr[6] + ' | ' + wordsArr[8],
                    key: wordsArr[0] + '-*-' + wordsArr[2] + '-*-'
                        + wordsArr[4] + '-*-' + wordsArr[5] + '-*-' + wordsArr[7] + '-*-' + wordsArr[9],
                }
            })
        }
        console.log('onCheck', modalTreeData);
        this.setState({
            checkedKeys,
            modalTreeData: modalTreeData
        });
    }

    cleanTreeChecked = () => {
        this.setState({
            checkedKeys: [],
            modalTreeData: []
        });
    }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item} >
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })

    showModal = () => {
        this.setState({ modalVisible: true })
    }

    closeModal = () => {
        this.setState({ modalVisible: false })
    }

    rangePickerOnChange = (date, dateString) => {
        console.log(date, dateString)
        this.setState({
            startDate: date[0],
            endDate: date[1]
        }, () => {
            this.refreshData();
        })
    }

    addFromHistoryHandleClick() {
        // console.log(this.modalFormRef.current)
        this.modalFormRef.current.validateFields((err, date) => {
            if (!err) {
                this.setState({ submitLoading: true });
                let startDate = date.datePeriod[0].format('YYYY-MM-DD');
                let endDate = date.datePeriod[1].format('YYYY-MM-DD');
                let values = [];
                this.state.modalTreeData.forEach((item) => {
                    let arr = item.key.split('-*-');
                    values.push({
                        classId: arr[0],
                        cycle: arr[2],
                        inspectitempointrelationId: arr[4],
                        index: arr[5]
                    })
                })
                addInspectPlanFromHistoryApi(parseInt(sessionStorage.getItem("departmentId")), startDate, endDate, values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                modalVisible: false,
                                submitLoading: false,
                                checkedKeys: [],
                                modalTreeData: [],
                            }, () => {
                                this.state.that.refreshData();
                                message.success("新增成功!");
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                submitLoading: false,
                                msg: "提交失败!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        })
    }

    disabledDate(current) {
        return current > moment().endOf('day');
    }

    render() {

        return (
            <Drawer
                bodyStyle={{ paddingBottom: 80 }}
                width={800}
                title={'历史巡检计划'}
                visible={this.state.visible}
                onClose={this.handleDrawerCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <span style={{ fontSize: 16 }}>时间范围：</span>
                <RangePicker
                    format="YYYY-MM-DD"
                    defaultValue={[this.state.startDate, this.state.endDate]}
                    onChange={this.rangePickerOnChange}
                    disabledDate={this.disabledDate} />
                <Skeleton loading={this.state.confirmLoading} active>
                    {this.state.treeData.length === 0 ?
                        <Empty style={{ marginTop: 200 }} />
                        :
                        <Fragment>
                            <Button
                                style={{ float: 'right', marginTop: 4, marginLeft: 24, color: '#fa8c16', borderColor: '#fa8c16' }}
                                onClick={this.cleanTreeChecked}
                                shape="round"
                                size='small'>
                                <Icon type="delete" theme="outlined" />清除选择
                            </Button>
                            <Tree
                                style={{ marginTop: 12 }}
                                checkable
                                onExpand={this.onExpand}
                                expandedKeys={this.state.expandedKeys}
                                autoExpandParent={this.state.autoExpandParent}
                                onCheck={this.onCheck}
                                checkedKeys={this.state.checkedKeys}
                                selectable={false}
                            >
                                {this.renderTreeNodes(this.state.treeData)}
                            </Tree>
                        </Fragment>
                    }
                    {this.state.alertVisible ?
                        (
                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                        ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    <Button size="large" style={{ marginRight: 20 }}
                        onClick={this.handleDrawerCancel.bind(this)}>关闭</Button>
                    <Button type="primary" size="large" loading={this.state.confirmLoading}
                        disabled={this.state.checkedKeys.length === 0}
                        onClick={this.showModal}>快速新增计划</Button>
                </div>
                <Modal
                    destroyOnClose={true}
                    title={"快速新增巡检计划"}
                    visible={this.state.modalVisible}
                    onCancel={this.closeModal}
                    width={'800px'}
                    bodyStyle={{
                        maxHeight: 630,
                    }}
                    closable
                    footer={
                        <Fragment>
                            <Button size="large" style={{ marginRight: 20 }}
                                onClick={this.closeModal}>关闭</Button>
                            <Button key="submit" type="primary" size="large" loading={this.state.submitLoading}
                                onClick={this.addFromHistoryHandleClick.bind(this)}>提交</Button>
                        </Fragment>
                    }
                >
                    <AddInspectFromHistoryForm
                        ref={this.modalFormRef}
                        modalTreeData={this.state.modalTreeData} />
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Modal>
            </Drawer>
        )
    }
}

class addInspectFromHistoryForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modalTreeData: props.modalTreeData,
        }
    }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })

    disabledDate(current) {
        // Can not select days before today and today
        return current < moment().endOf('day');
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        }
        return (
            <Fragment>
                <div style={{
                    fontSize: 14,
                    marginLeft: 28,
                    color: 'rgba(0, 0, 0, 0.85)',
                }}>
                    <span style={{
                        marginRight: 4,
                        color: '#f5222d',
                        fontSize: 14,
                        fontFamily: 'SimSun, sans-serif',
                        lineHeight: 1
                    }}>*</span>所选历史计划：
                </div>
                <Tree
                    style={{ marginLeft: 12, overflow: 'auto', maxHeight: 500 }}
                    checkable={false}
                    selectable={false}>
                    {this.renderTreeNodes(this.state.modalTreeData)}
                </Tree>
                <Form style={{ marginTop: 12 }}>
                    <FormItem
                        label='日期时段'
                        {...formItemLayout}>
                        {getFieldDecorator("datePeriod", {
                            rules: [{
                                type: 'array',
                                required: true,
                                message: "请输入日期时段!"
                            }]
                        })(
                            <RangePicker
                                format="YYYY-MM-DD"
                                disabledDate={this.disabledDate} />
                        )}
                    </FormItem>
                </Form>
            </Fragment>
        )
    }
}
const AddInspectFromHistoryForm = Form.create()(addInspectFromHistoryForm);

class InspectPlanInnerTable extends Component {
    constructor(props) {
        super(props);

        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            filteredInfo: null,
            sortedInfo: null,
            tableLoading: true,
            teamId: props.teamId,
            teamName: props.teamName,
            that: props.that,
            innerData: [],
            // cycleFilter: [{
            //     text: '年', value: '年'
            // }, {
            //     text: '月', value: '月'
            // }, {
            //     text: '周', value: '周'
            // }, {
            //     text: '日', value: '日'
            // }],
            updateVisible: false,
        }
    }

    componentDidMount() {
        this.refreshData();
        this.props.onRef(this);
    }

    componentWillReceiveProps(props) {
        // console.log('props', props)
        this.setState({
            teamId: props.teamId,
            teamName: props.teamName,
            that: props.that,
        });
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        inspectPlanMakeByClassIdApi(
            parseInt(sessionStorage.getItem("departmentId")), this.state.teamId)
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    innerData.push({
                        key: index + 1,
                        checkpointId: item.checkpointId,
                        address: item.address,
                        startDate: item.startDate,
                        endDate: item.endDate,
                        cycle: item.cycle,
                        symbol: item.symbol,
                        rowSpan: 0,
                    });
                });
                //为了表格的列合并
                let count = 1;
                for (let i = innerData.length - 1; i >= 0; i--) {
                    if (i == 0) {
                        innerData[i].rowSpan = count;
                        break;
                    }
                    if (innerData[i].checkpointId == innerData[i - 1].checkpointId) {
                        count++;
                    } else {
                        innerData[i].rowSpan = count;
                        count = 1;
                    }
                }
                this.setState({
                    innerData: innerData,
                    tableLoading: false
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    showUpdateDrawer(record) {
        this.setState({
            updateVisible: true,
            currentCheckpointId: record.checkpointId,
            currentSymbol: record.symbol,
            currentAddress: record.address,
            currentCycle: record.cycle,
            currentStartDate: record.startDate,
            currentEndDate: record.endDate
        })
    }

    // handleUpdateDrawerCancel() {
    //     this.setState({
    //         updateVisible: false,
    //     })
    // }
    handleAddCancel() {
        this.setState({
            updateVisible: false,
        })
    }


    handleDelete(record, symbol) {
        this.setState({
            tableLoading: true
        });
        deleteInspectPlanBySymbolApi(
            parseInt(sessionStorage.getItem("departmentId")), symbol, this.state.teamId, parseInt(record.checkpointId))
            .then((res) => {
                if (res.data == "success") {
                    this.setState({
                        tableLoading: false
                    });
                    message.success("删除成功!");
                    //this.refreshData();
                    this.state.that.refreshData();
                } else {
                    this.setState({
                        tableLoading: false
                    });
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        // let json = {
        //     schoolId: parseInt(sessionStorage.getItem("departmentId")),
        //     symbol: symbol
        // }
        // deleteInspectPlanByClassIdApi(json).then((res) => {

        //     console.log("deleteInspectPlanByClassIdApi=====================", res)
        //     if (res.data == "success") {
        //         message.success("删除成功!");
        //         this.refreshData();
        //         this.state.that.refreshData();
        //     } else {
        //         message.error('删除失败,请稍后再试!');
        //     }
        // })
        // .catch((e) => {
        //     if (e.response) {
        //         //请求已发出，服务器返回状态码不是2xx。
        //         console.info(e.response.data)
        //         console.info(e.response.status)
        //         console.info(e.response.headers)
        //     } else if (e.request) {
        //         // 请求已发出，但没有收到响应
        //         // e.request 在浏览器里是一个XMLHttpRequest实例，
        //         // 在node中是一个http.ClientRequest实例
        //         console.info(e.request)
        //     } else {
        //         //发送请求时异常，捕捉到错误
        //         console.info('error', e.message)
        //     }
        //     console.info(e.config)
        // });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }


    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        const innerColumns = [{
            title: '排查点地址',
            dataIndex: 'address',
            key: 'address',
            width: '30%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa' }} />,
            onFilter: (value, record) => record.address.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            },
            render: (text, record, index) => {
                const obj = {
                    children: text,
                    props: {},
                };
                obj.props.rowSpan = record.rowSpan;

                return obj;
            },
        }, {
            title: '日期时段',
            dataIndex: 'datePeriod',
            key: 'datePeriod',
            width: '30%',
            render: (text, record) => {
                return (record.startDate + ' ~ ' + record.endDate);
            },
        }, {
            title: '周期',
            dataIndex: 'cycle',
            key: 'cycle',
            width: '10%',
            render: (text, record) => {
                return ('每' + record.cycle);
            },
            // filters: this.state.cycleFilter,
            // filteredValue: filteredInfo.cycle || null,
            // onFilter: (value, record) => record.cycle == value,
            // filterIcon: filtered =>
            //     <Icon type="filter"
            //         style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
        }, {
            title: "操作详情",
            key: "action",
            width: '30%',
            render: (text, record) => (
                <span>
                    <a href="javascript:;" onClick={this.showUpdateDrawer.bind(this, record)}>项目详情/修改</a>
                    <Divider type="vertical" />
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDelete(record, record.symbol)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];
        return (
            <div>
                <Table
                    columns={innerColumns}
                    dataSource={this.state.innerData}
                    pagination={false}
                    size='small'
                    onChange={this.handleChange}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    bordered={true}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                />
                {/* <InspectPlanItemUpdateDrawer
                    visible={this.state.updateVisible}
                    currentCheckpointId={this.state.currentCheckpointId}
                    currentSymbol={this.state.currentSymbol}
                    currentTeamId={this.state.teamId}
                    that={this} /> */}
                <UpdateInspectPlanForm
                    visible={this.state.updateVisible}
                    teamId={this.state.teamId}
                    teamName={this.state.teamName}
                    checkpointId={this.state.currentCheckpointId}
                    symbol={this.state.currentSymbol}
                    address={this.state.currentAddress}
                    cycle={this.state.currentCycle}
                    startDate={this.state.currentStartDate}
                    endDate={this.state.currentEndDate}
                    that={this}
                />
            </div>
        )
    }
}
class updateInspectPlanForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            checkItemTreeData: [],
            checkItemTreeData2: [],
            expandedKeys: [],
            expandedKeys2: [],
            autoExpandParent: true,
            autoExpandParent2: true,
            checkedKeys: [],
            checkedKeys2: [],
            selectedKeys: [],
            selectedKeys2: [],
            allTeamOptions: [],
            allCheckpointOptions: [],
            allCycleOptions: ['年', '月', '周', '日'],
            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语
            visible: props.visible,
            that: props.that,
            currentStep: 0,
            teamId: props.teamId,
            teamName: props.teamName,
            checkpointId: props.checkpointId,
            symbol: props.symbol,
            address: props.address,
            cycle: props.cycle,
            startDate: props.startDate,
            endDate: props.endDate
        };
    }

    componentDidMount() {

    }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
            teamId: props.teamId,
            teamName: props.teamName,
            checkpointId: props.checkpointId,
            symbol: props.symbol,
            address: props.address,
            cycle: props.cycle,
            startDate: props.startDate,
            endDate: props.endDate,
            that: props.that,
        })
    }


    refreshData() {
    }

    handleAddClick() {
        if (this.state.checkedKeys.length == 0 || this.state.checkedKeys2.length == 0) {
            this.setState({
                alertVisible: true,
                msg: "请选择巡检项目或者巡检内容！", //提交失败时的提示语  
            });
        } else {
            this.setState({
                confirmLoading: true
            });
            let checkedItemValues = [];
            this.state.checkedKeys2.forEach((value, index) => {
                let temp = value.split('-');
                if (temp.length == 3) {
                    checkedItemValues.push(value);
                }
            });
            updateAndAddInspectPlanApi(parseInt(sessionStorage.getItem("departmentId")),
                this.state.teamId, this.state.currentStartDate, this.state.currentEndDate,
                this.state.currentCycle, checkedItemValues, this.state.checkpointId, this.state.symbol)
                .then((res) => {
                    console.log("updateAndAddInspectPlanApi", res.data)
                    if (res.data == "success") {
                        message.success("修改成功!");
                        this.setState({
                            confirmLoading: false,
                            alertVisible: false,
                        });
                        this.next();
                        this.state.that.refreshData();
                    } else if (res.data == "fail") {
                        message.error("修改失败")
                        this.setState({
                            alertVisible: true,
                            confirmLoading: false,
                            msg: "修改失败,请检查信息或稍后再试!"
                        });
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
        }
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({
            alertVisible: false
        });
    }

    onExpand = (expandedKeys) => {
        console.log(expandedKeys)
        this.setState({
            expandedKeys:expandedKeys,
            autoExpandParent: false,
        });
    }
    onExpand2 = (expandedKeys) => {
        this.setState({
            expandedKeys2: expandedKeys,
            autoExpandParent2: false,
        });
    }

    onCheck = (checkedKeys) => {
        console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    }
    onCheck2 = (checkedKeys) => {
        console.log('onCheck2', checkedKeys);
        console.log('currentCheckpointId', this.state.currentCheckpointId);
        this.setState({
            checkedKeys2: checkedKeys
        });
    }

    // onSelect = (selectedKeys, info) => {
    //     console.log('onSelect', info);
    //     this.setState({ selectedKeys });
    // }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })
    renderTreeNodes2 = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes2(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })


    next = (e) => {
        if (this.state.currentStep == 0) {
            e.preventDefault();
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    this.setState({
                        currentStartDate: values.datePeriod[0].format('YYYY-MM-DD'),
                        currentEndDate: values.datePeriod[1].format('YYYY-MM-DD'),
                        currentCycle: values.cycle,
                        confirmLoading: true,
                    });
                    getInspectPlanItemBySymbol(this.state.checkpointId, this.state.symbol, this.state.teamId, parseInt(sessionStorage.getItem("departmentId")))
                        .then((res) => {
                            let treeData = [];
                            let checkedKeys = [];
                            res.data.forEach((item, index) => {
                                let category = {
                                    title: item.categoryName,
                                    key: item.categoryId,
                                    children: []
                                }
                                item.items.forEach((item2, index2) => {
                                    category.children.push({
                                        title: item2.item,
                                        key: item.categoryId + '-' + item2.item + '-' + item.categoryName,
                                    });
                                    if (item2.used == 1) {
                                        checkedKeys.push(item.categoryId + '-' + item2.item + '-' + item.categoryName)
                                    }
                                })
                                treeData.push(category);
                            });
                            this.setState({
                                checkItemTreeData: treeData,
                                checkedKeys: checkedKeys,
                                // expandedKeys: checkedKeys,
                                autoExpandParent: true,
                                confirmLoading: false,
                            });
                        }).catch((e) => {
                            if (e.response) {
                                //请求已发出，服务器返回状态码不是2xx。
                                console.info(e.response.data)
                                console.info(e.response.status)
                                console.info(e.response.headers)
                            } else if (e.request) {
                                // 请求已发出，但没有收到响应
                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                // 在node中是一个http.ClientRequest实例
                                console.info(e.request)
                            } else {
                                //发送请求时异常，捕捉到错误
                                console.info('error', e.message)
                            }
                            console.info(e.config)
                        });

                    const currentStep = this.state.currentStep + 1;
                    this.setState({ currentStep: currentStep });
                }
            });
        } else if (this.state.currentStep == 1) {
            console.log("symbol", this.state.symbol)
            console.log("startDate", this.state.currentStartDate)
            console.log("cycle", this.state.currentCycle)
            if (this.state.checkedKeys.length != 0) {
                let treeData2 = [];
                let checkedKeys2 = []
                this.setState({
                    confirmLoading: true
                })
                getInspectPlanItemAndContentUpdate(parseInt(sessionStorage.getItem("departmentId")),
                    this.state.symbol, this.state.checkedKeys).then((res) => {
                    console.log("treeData2", res.data)
                    res.data.forEach((item, index) => {
                        let categoryItem
                        categoryItem = {
                            title: item.categoryItem.split("-")[1] + "-" + item.categoryItem.split("-")[2],
                            key: item.categoryItem.split("-")[0] + '-' + item.categoryItem.split("-")[2],
                            children: []
                        }
                        item.contentList.forEach((item2, index2) => {
                            categoryItem.children.push({
                                title: item2.content,
                                key: item.categoryItem.split("-")[0] + '-' + item2.inspectitemId + '-' + item.categoryItem.split("-")[2],
                            })
                            if (item2.used == 1) {
                                checkedKeys2.push(item.categoryItem.split("-")[0] + '-' + item2.inspectitemId + '-' + item.categoryItem.split("-")[2])
                            }
                        })
                        treeData2.push(categoryItem);
                    });
                    this.setState({
                        checkItemTreeData2: treeData2,
                        confirmLoading: false,
                        checkedKeys2: checkedKeys2,
                        autoExpandParent2: true,
                        // expandedKeys2: checkedKeys2,
                    });
                });
                const currentStep = this.state.currentStep + 1;
                this.setState({ currentStep: currentStep });
            } else {
                message.error("请选择巡检项！")
            }
        } else if (this.state.currentStep == 2) {
            if (this.state.checkedKeys.length != 0) {
                const currentStep = this.state.currentStep + 1;
                this.setState({ currentStep: currentStep });
            } else {
                message.error("请选择巡检内容！")
            }
        }

    }

    prev = () => {
        const currentStep = this.state.currentStep - 1;
        this.setState({
            currentStep: currentStep,
            // checkedKeys: [],
        });

    }

    handleAddCancel = () => {
        //父类关闭
        this.state.that.handleAddCancel();


        this.props.form.resetFields();
        this.setState({
            currentStep: 0,
            checkedKeys: [],
            checkedKeys2: [],
            // currentClassId: undefined,
            // currentCheckpointId: undefined,
            // currentStartDate: undefined,
            // currentEndDate: undefined,
            // currentCycle: undefined,
            // alertVisible: false 
        });

    }

    disabledDate(current) {
        // Can not select days before today and today
        return current < moment().subtract(1, 'day');
    }

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        let cycleOptions = this.state.allCycleOptions.map((d, index) => <Option value={d} key={index}>{'每' + d}</Option>);
        let step = (
            <Steps
                current={this.state.currentStep}
                style={{
                    marginBottom: 30,
                }}>
                <Step title="修改部分信息" description="请按照提示填写" />
                <Step title="修改巡检项目" description="可多选" />
                <Step title="修改巡检内容" description="可多选" />
                <Step title="完成" />
            </Steps>
        );

        let drawerContent;
        if (this.state.currentStep == 0) {
            drawerContent = (
                <div>
                    {step}
                    <Form onSubmit={this.next}>
                        <FormItem
                            label='可选班组'
                            {...formItemLayout}>
                            {getFieldDecorator("classId", {
                                initialValue: this.state.teamName,
                                rules: [{
                                    required: true,
                                    message: "请选择班组!"
                                }]
                            })(
                                <Select
                                    size="large"
                                    placeholder="选择班组"
                                    disabled={true}>
                                    {this.state.allTeamOptions}
                                </Select>
                            )}
                        </FormItem>
                        <FormItem
                            label='地点'
                            {...formItemLayout}>
                            {getFieldDecorator("checkpointId", {
                                initialValue: this.state.address,
                                rules: [{
                                    required: true,
                                    message: "请选择地点!"
                                }]
                            })(
                                <Select
                                    size="large"
                                    placeholder="选择地点"
                                    disabled={true}>
                                    {this.state.allCheckpointOptions}
                                </Select>
                            )}
                        </FormItem>

                        <FormItem
                            label='日期时段'
                            {...formItemLayout}>
                            {getFieldDecorator("datePeriod", {
                                initialValue: [moment(this.state.startDate, 'YYYY-MM-DD'), moment(this.state.endDate, 'YYYY-MM-DD')],
                                rules: [{
                                    type: 'array',
                                    required: true,
                                    message: "请输入日期时段!"
                                }]
                            })(
                                <RangePicker
                                    size="large"
                                    format="YYYY-MM-DD"
                                    disabledDate={this.disabledDate} />
                            )}
                        </FormItem>
                        <FormItem
                            label='计划周期'
                            {...formItemLayout}>
                            {getFieldDecorator("cycle", {
                                initialValue: this.state.cycle,
                                rules: [{
                                    required: true,
                                    message: "请输入计划周期!"
                                }]
                            })(
                                <Select
                                    size="large"
                                    placeholder="选择周期">
                                    {cycleOptions}
                                </Select>
                            )}
                        </FormItem>
                    </Form>
                </div>
            );
        } else if (this.state.currentStep == 1) {
            drawerContent = (
                <div>
                    {step}
                    {
                        this.state.checkItemTreeData.length == 0 ? (
                            <Alert
                                message={'没有符合的巡检项目，请重新选择班组与排查点地址 或 配置排查点规划！'}
                                type="error"
                                closable
                                afterClose={this.handleClose.bind(this)} />
                        ) : null
                    }
                    <Tree
                        checkable
                        // onExpand={this.onExpand}
                        // defaultCheckedKeys={this.state.expandedKeys}
                        // expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                        defaultExpandAll
                    >
                        {this.renderTreeNodes(this.state.checkItemTreeData)}
                    </Tree>
                </div>
            )
        } else if (this.state.currentStep == 2) {
            drawerContent = (
                <div>
                    {step}
                    <Tree
                        checkable
                        // onExpand={this.onExpand2}
                        // expandedKeys={this.state.expandedKeys2}
                        autoExpandParent={this.state.autoExpandParent2}
                        onCheck={this.onCheck2}
                        checkedKeys={this.state.checkedKeys2}
                        onSelect={this.onSelect2}
                        selectedKeys={this.state.selectedKeys2}
                        defaultExpandAll
                    >
                        {this.renderTreeNodes2(this.state.checkItemTreeData2)}
                    </Tree>
                </div>
            )
        } else if (this.state.currentStep == 3) {
            drawerContent = (
                <div>
                    {step}
                    <div style={{
                        textAlign: 'center',
                        width: '100%',
                        marginTop: '200px',
                    }}>
                        <IconFont type='icon-locationiconsuccess' style={{ fontSize: '10em' }} />
                        <div style={{ fontSize: 20, marginTop: '20px' }}>操作成功!</div>
                    </div>
                </div>
            )
        }

        let footerButton;
        if (this.state.currentStep == 0) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large"
                        onClick={this.next}>下一步</Button>
                </div>
            )
        } else if (this.state.currentStep == 1) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" onClick={this.prev}
                        style={{ marginRight: 20 }} >上一步</Button>
                    <Button type="primary" size="large" onClick={this.next}
                        style={{ marginRight: 20 }} >下一步</Button>
                </div>
            )
        } else if (this.state.currentStep == 2) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" onClick={this.prev}
                        style={{ marginRight: 20 }} >上一步</Button>
                    <Button type="primary" size="large" loading={this.state.confirmLoading}
                        onClick={this.handleAddClick.bind(this)}>更新</Button>
                </div>
            )
        } else if (this.state.currentStep == 3) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                </div>
            )
        }




        return (
            <Drawer
                bodyStyle={{ paddingBottom: 80 }}
                width={800}
                title={'新增计划'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    {drawerContent}
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        );
    }
}
const UpdateInspectPlanForm = Form.create()(updateInspectPlanForm);

class InspectPlanItemUpdateDrawer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: [],
            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            visible: props.visible,
            that: props.that,
            currentCheckpointId: props.currentCheckpointId,
            currentSymbol: props.currentSymbol,
            currentTeamId: props.currentTeamId,
            isUpdateOpen: false,
        };
    }

    // componentDidMount() {
    //     this.refreshData();
    // }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
            that: props.that,
            currentCheckpointId: props.currentCheckpointId,
            currentSymbol: props.currentSymbol,
            currentTeamId: props.currentTeamId,
        });
        if (props.visible) {
            this.refreshData(props.currentCheckpointId, props.currentSymbol, props.currentTeamId);
        }

    }

    refreshData(checkpointId, symbol, classId) {
        this.setState({
            confirmLoading: true,
        });
        getInspectPlanItemBySymbol(checkpointId, symbol, classId,
            parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let treeData = [];
                let checkedKeys = [];
                res.data.forEach((item, index) => {
                    let category = {
                        title: item.categoryName,
                        key: item.categoryId,
                        children: []
                    }
                    item.items.forEach((item2, index2) => {
                        category.children.push({
                            title: item2.item,
                            key: item.categoryId + "-" + item2.item + "-" + item2.id
                        });
                        if (item2.used == 1) {
                            checkedKeys.push(item.categoryId + "-" + item2.item + "-" + item2.id)
                        }
                    })
                    treeData.push(category);
                });
                this.setState({
                    treeData: treeData,
                    checkedKeys: checkedKeys,
                    expandedKeys: checkedKeys,
                    autoExpandParent: true,
                    confirmLoading: false,
                });
            }).catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleUpdateClick() {
        this.setState({
            confirmLoading: true
        });
        let checkedKeysValues = [];
        this.state.checkedKeys.forEach((value, index) => {
            let temp = value.split('-');
            if (temp.length == 3) {
                checkedKeysValues.push(parseInt(temp[2]));
            }
        });
        updateInspectPlanApi(this.state.currentTeamId, this.state.currentCheckpointId,
            this.state.currentSymbol, checkedKeysValues, parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                if (res.data == "success") {
                    message.success("更新成功!");
                    this.setState({
                        confirmLoading: false,
                        isUpdateOpen: !this.state.isUpdateOpen,
                    });
                    this.state.that.handleUpdateCancel();
                    this.state.that.refreshData();
                } else if (res.data == "fail") {
                    this.setState({
                        alertVisible: true,
                        confirmLoading: false,
                        msg: "修改失败,请检查信息或稍后再试!"
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleUpdateDrawerCancel() {
        this.setState({
            isUpdateOpen: false,
        });
        this.state.that.handleUpdateDrawerCancel();
    }

    isUpdateOpenChange() {
        if (this.state.isUpdateOpen) {
            this.refreshData(this.state.currentCheckpointId, this.state.currentSymbol);
        }
        this.setState({
            isUpdateOpen: !this.state.isUpdateOpen,
        });
    }



    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }

    onCheck = (checkedKeys) => {
        //console.log('onCheck', checkedKeys);
        if (this.state.isUpdateOpen) {
            this.setState({ checkedKeys });
        }
    }

    onSelect = (selectedKeys, info) => {
        //console.log('onSelect', info);
        //this.setState({ selectedKeys });
    }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })

    render() {

        return (
            <Drawer
                bodyStyle={{ paddingBottom: 80 }}
                width={600}
                title={'修改项目详情'}
                visible={this.state.visible}
                onClose={this.handleUpdateDrawerCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Alert
                    message="注意事项"
                    description='若需修改，请先点击下方的“点击修改”按钮，修改项目详情之后，点击“提交”按钮。'
                    type="info"
                    style={{ marginBottom: 10 }}
                    showIcon />
                <Skeleton loading={this.state.confirmLoading} active>
                    <Tree
                        checkable
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                    >
                        {this.renderTreeNodes(this.state.treeData)}
                    </Tree>
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    <Button size="large" style={{ marginRight: 20 }}
                        onClick={this.handleUpdateDrawerCancel.bind(this)}>关闭</Button>
                    <Button type="primary" size="large"
                        loading={this.state.confirmLoading} style={{ marginRight: 20 }}
                        onClick={this.isUpdateOpenChange.bind(this)}>
                        <Icon type={this.state.isUpdateOpen ? 'unlock' : 'lock'} />
                        {this.state.isUpdateOpen ? '点击锁定' : '点击修改'}
                    </Button>
                    <Button type="primary" size="large" loading={this.state.confirmLoading}
                        disabled={!this.state.isUpdateOpen}
                        onClick={this.handleUpdateClick.bind(this)}>提交</Button>
                </div>
            </Drawer>
        )
    }
}

class addInspectPlanForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            checkItemTreeData: [],
            checkItemTreeData2: [],
            expandedKeys: [],
            expandedKeys2: [],
            autoExpandParent: true,
            autoExpandParent2: true,
            checkedKeys: [],
            checkedKeys2: [],
            selectedKeys: [],
            selectedKeys2: [],

            allTeamOptions: [],
            allCheckpointOptions: [],
            allCycleOptions: ['年', '月', '周', '日'],

            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语

            visible: props.visible,
            that: props.that,
            currentStep: 0,

            // currentStartDate: (new Date()).format("YYYY-MM-DD"),
            // currentEndDate: (new Date()).format("YYYY-MM-DD"),
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
            that: props.that,
        });
    }


    refreshData() {
        this.setState({
            confirmLoading: true,
        })
        teamOptionsBySchoolAndType(parseInt(sessionStorage.getItem("departmentId")), 2)
            .then((res) => {
                let allTeamOptions = [];
                res.data.forEach((item, index) => {
                    allTeamOptions.push({
                        teamId: item.id,
                        className: item.name,
                        text: item.name + '  |  负责人：' + item.realName+ '  |  ：' +item.category
                    })
                });
                let options = allTeamOptions.map((d, index) => <Option value={d.teamId + '-' + d.className} key={index}>{d.text}</Option>);
                this.setState({
                    allTeamOptions: options,
                    confirmLoading: false,
                })
                //console.log(options);
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getInspectItemPointRelationBySchoolApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let allCheckpointOptions = [];
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    allCheckpointOptions.push({
                        id: item.id,
                        address: item.address,
                    });
                });
                let options = allCheckpointOptions.map((d, index) => <Option value={d.id + '-' + d.address} key={index}>{d.address}</Option>);
                this.setState({
                    allCheckpointOptions: options,
                    confirmLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleAddClick() {
        if (this.state.checkedKeys.length == 0 || this.state.checkedKeys2.length == 0) {
            this.setState({
                alertVisible: true,
                msg: "请选择巡检项目或者巡检内容！", //提交失败时的提示语  
            });
        } else {
            this.setState({
                confirmLoading: true
            });
            let checkedItemValues = [];
            this.state.checkedKeys2.forEach((value, index) => {
                let temp = value.split('-');
                if (temp.length == 3) {
                    checkedItemValues.push(value);
                }
            });
            addInspectPlanApi(parseInt(sessionStorage.getItem("departmentId")),
                this.state.currentClassId, this.state.currentClassName, this.state.currentStartDate, this.state.currentEndDate,
                this.state.currentCycle, checkedItemValues, this.state.currentCheckpointId, this.state.currentCheckpoint)
                .then((res) => {
                    console.log("addInspectPlanApi", res.data)
                    if (res.data == "success") {
                        message.success("添加成功!");
                        this.setState({
                            confirmLoading: false,
                            alertVisible: false,
                        });
                        this.next();
                        this.state.that.refreshData();
                    } else if (res.data == "fail") {
                        message.error("添加失败")
                        this.setState({
                            alertVisible: true,
                            confirmLoading: false,
                            msg: "提交失败,请检查信息或稍后再试!"
                        });
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出���服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
        }
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({
            alertVisible: false
        });
    }

    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }
    onExpand2 = (expandedKeys) => {
        this.setState({
            expandedKeys2: expandedKeys,
            autoExpandParent2: false,
        });
    }

    onCheck = (checkedKeys) => {
        console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    }
    onCheck2 = (checkedKeys) => {
        console.log('onCheck2', checkedKeys);
        console.log('currentCheckpointId', this.state.currentCheckpointId);
        this.setState({
            checkedKeys2: checkedKeys
        });
    }

    // onSelect = (selectedKeys, info) => {
    //     console.log('onSelect', info);
    //     this.setState({ selectedKeys });
    // }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })
    renderTreeNodes2 = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes2(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })

    next = (e) => {
        if (this.state.currentStep == 0) {
            e.preventDefault();
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    this.setState({
                        currentClassName: values.classId.split("-")[1],
                        currentClassId: values.classId.split("-")[0],
                        currentCheckpointId: values.checkpointId.split("-")[0],
                        currentCheckpoint: values.checkpointId.split("-")[1],
                        currentStartDate: values.datePeriod[0].format('YYYY-MM-DD'),
                        currentEndDate: values.datePeriod[1].format('YYYY-MM-DD'),
                        currentCycle: values.cycle,
                        currentClass:values.classId,
                        currentPlace:values.checkpointId,
                        confirmLoading: true,
                    });
                    getItemWithTreeForAddInspectPlanApi(parseInt(sessionStorage.getItem("departmentId")), values.classId.split("-")[0])
                        .then((res) => {
                            let treeData = [];
                            let checkedKeys = []
                            res.data.forEach((item, index) => {
                                let category = {
                                    title: item.categoryName,
                                    key: item.categoryId,
                                    children: []
                                }
                                item.items.forEach((item2, index2) => {
                                    if (item2.isCheck == 1) {
                                        category.children.push({
                                            title: item2.item,
                                            key: item.categoryId + '-' + item2.item + '-' + item.categoryName,
                                            // disabled: true,
                                        })
                                        checkedKeys.push(item.categoryId + '-' + item2.item + '-' + item.categoryName)
                                    } else {
                                        category.children.push({
                                            title: item2.item,
                                            key: item.categoryId + '-' + item2.item + '-' + item.categoryName,
                                        })
                                    }
                                })
                                treeData.push(category);
                            });
                            console.log('treeData', treeData);
                            this.setState({
                                checkItemTreeData: treeData,
                                checkedKeys: checkedKeys,
                                // expandedKeys: checkedKeys,
                                autoExpandParent: true,
                                confirmLoading: false,
                            });
                        })
                        .catch((e) => {
                            if (e.response) {
                                //请求已发出，服务器返回状态码不是2xx。
                                console.info(e.response.data)
                                console.info(e.response.status)
                                console.info(e.response.headers)
                            } else if (e.request) {
                                // 请求已发出，但没有收到响应
                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                // 在node中是一个http.ClientRequest实例
                                console.info(e.request)
                            } else {
                                //发送请求时异常，捕捉到错误
                                console.info('error', e.message)
                            }
                            console.info(e.config)
                        });

                    const currentStep = this.state.currentStep + 1;
                    this.setState({ currentStep: currentStep });
                }
            });
        } else if (this.state.currentStep == 1) {
            console.log("checkedKeys", this.state.checkedKeys)
            if (this.state.checkedKeys.length != 0) {
                let treeData2 = [];
                let checkedKeys2 = []
                this.setState({
                    confirmLoading: true
                })
                getInspectItemContentTree(parseInt(sessionStorage.getItem("departmentId")), this.state.checkedKeys).then((res) => {
                    console.log("treeData2", res.data)
                    res.data.forEach((item, index) => {
                        let categoryItem
                        categoryItem = {
                            title: item.categoryItem.split("-")[1] + "-" + item.categoryItem.split("-")[2],
                            key: item.categoryItem.split("-")[0] + '-' + item.categoryItem.split("-")[2],
                            children: []
                        }
                        item.contentList.forEach((item2, index2) => {
                            if (item2.isCheck == 1) {
                                categoryItem.children.push({
                                    title: item2.content,
                                    key: item.categoryItem.split("-")[0] + '-' + item2.inspectitemId + '-' + item.categoryItem.split("-")[2],
                                })
                                checkedKeys2.push(item.categoryItem.split("-")[0] + '-' + item2.inspectitemId + '-' + item.categoryItem.split("-")[2])
                            } else {
                                categoryItem.children.push({
                                    title: item2.content,
                                    key: item.categoryItem.split("-")[0] + '-' + item2.inspectitemId + '-' + item.categoryItem.split("-")[2],
                                })
                            }
                        })
                        treeData2.push(categoryItem);
                    });
                    this.setState({
                        checkItemTreeData2: treeData2,
                        confirmLoading: false,
                        checkedKeys2: checkedKeys2,
                        autoExpandParent2: true,
                        // expandedKeys2: checkedKeys2
                    });
                })
                const currentStep = this.state.currentStep + 1;
                this.setState({ currentStep: currentStep });
            } else {
                message.error("请选择巡检项！")
            }
        } else if (this.state.currentStep == 2) {
            if (this.state.checkedKeys.length != 0) {
                const currentStep = this.state.currentStep + 1;
                this.setState({ currentStep: currentStep });
            } else {
                message.error("请选择巡检内容！")
            }
        }

    }

    prev = () => {
        const currentStep = this.state.currentStep - 1;
        this.setState({
            currentStep: currentStep,
            // checkedKeys: [],
        });

    }

    handleAddCancel = () => {
        //父类关闭
        this.state.that.handleAddCancel();


        // this.props.form.resetFields();
        this.setState({
            currentStep: 0,
            checkedKeys: [],
            checkedKeys2: [],
            currentClassId: undefined,
            currentCheckpointId: undefined,
            currentStartDate: undefined,
            currentEndDate: undefined,
            currentCycle: undefined,
            alertVisible: false
        });

    }

    disabledDate(current) {
        // Can not select days before today and today
        return current < moment().subtract(1, 'day');
    }


    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        let cycleOptions = this.state.allCycleOptions.map((d, index) => <Option value={d} key={index}>{'每' + d}</Option>);
        let step = (
            <Steps
                current={this.state.currentStep}
                style={{
                    marginBottom: 30,
                }}>
                <Step title="填写部分信息" description="请按照提示填写" />
                <Step title="选择巡检项目" description="可多选" />
                <Step title="选择巡检内容" description="可多选" />
                <Step title="完成" />
            </Steps>
        );

        let drawerContent;
        if (this.state.currentStep == 0) {
            drawerContent = (
                <div>
                    {step}
                    <Form onSubmit={this.next}>
                        <FormItem
                            label='可选班组'
                            {...formItemLayout}>
                            {getFieldDecorator("classId", {
                                initialValue: this.state.currentClass,
                                rules: [{
                                    required: true,
                                    message: "请选择班组!"
                                }]
                            })(
                                <Select
                                    size="large"
                                    placeholder="选择班组">
                                    {this.state.allTeamOptions}
                                </Select>
                            )}
                        </FormItem>
                        <FormItem
                            label='地点'
                            {...formItemLayout}>
                            {getFieldDecorator("checkpointId", {
                                initialValue: this.state.currentPlace,
                                rules: [{
                                    required: true,
                                    message: "请选择地点!"
                                }]
                            })(
                                <Select
                                    size="large"
                                    placeholder="选择地点">
                                    {this.state.allCheckpointOptions}
                                </Select>
                            )}
                        </FormItem>
                        {this.state.currentStartDate == undefined ?
                            (
                                <FormItem
                                    label='日期时段'
                                    {...formItemLayout}>
                                    {getFieldDecorator("datePeriod", {
                                        rules: [{
                                            type: 'array',
                                            required: true,
                                            message: "请输入日期时段!"
                                        }]
                                    })(
                                        <RangePicker
                                            size="large"
                                            format="YYYY-MM-DD"
                                            disabledDate={this.disabledDate} />
                                    )}
                                </FormItem>
                            ) : (
                                <FormItem
                                    label='日期时段'
                                    {...formItemLayout}>
                                    {getFieldDecorator("datePeriod", {
                                        initialValue: [moment(this.state.currentStartDate, 'YYYY-MM-DD'), moment(this.state.currentEndDate, 'YYYY-MM-DD')],
                                        rules: [{
                                            type: 'array',
                                            required: true,
                                            message: "请输入日期时段!"
                                        }]
                                    })(
                                        <RangePicker
                                            size="large"
                                            format="YYYY-MM-DD"
                                            disabledDate={this.disabledDate} />
                                    )}
                                </FormItem>
                            )
                        }
                        <FormItem
                            label='计划周期'
                            {...formItemLayout}>
                            {getFieldDecorator("cycle", {
                                initialValue: this.state.currentCycle,
                                rules: [{
                                    required: true,
                                    message: "请输入计划周期!"
                                }]
                            })(
                                <Select
                                    size="large"
                                    placeholder="选择周期">
                                    {cycleOptions}
                                </Select>
                            )}
                        </FormItem>
                    </Form>
                </div>
            );
        } else if (this.state.currentStep == 1) {
            drawerContent = (
                <div>
                    {step}
                    {
                        this.state.checkItemTreeData.length == 0 ? (
                            <Alert
                                message={'没有符合的巡检项目，请重新选择班组与排查点地址 或 配置排查点规划！'}
                                type="error"
                                closable
                                afterClose={this.handleClose.bind(this)} />
                        ) : null
                    }
                    <Tree
                        checkable
                        // onExpand={this.onExpand}
                        // defaultCheckedKeys={this.state.expandedKeys}
                        // expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                        defaultExpandAll
                    >
                        {this.renderTreeNodes(this.state.checkItemTreeData)}
                    </Tree>
                </div>
            )
        } else if (this.state.currentStep == 2) {
            drawerContent = (
                <div>
                    {step}
                    <Tree
                        checkable
                        // onExpand={this.onExpand2}
                        // expandedKeys={this.state.expandedKeys2}
                        autoExpandParent={this.state.autoExpandParent2}
                        onCheck={this.onCheck2}
                        checkedKeys={this.state.checkedKeys2}
                        onSelect={this.onSelect2}
                        selectedKeys={this.state.selectedKeys2}
                        defaultExpandAll
                    >
                        {this.renderTreeNodes2(this.state.checkItemTreeData2)}
                    </Tree>
                </div>
            )
        } else if (this.state.currentStep == 3) {
            drawerContent = (
                <div>
                    {step}
                    <div style={{
                        textAlign: 'center',
                        width: '100%',
                        marginTop: '200px',
                    }}>
                        <IconFont type='icon-locationiconsuccess' style={{ fontSize: '10em' }} />
                        <div style={{ fontSize: 20, marginTop: '20px' }}>操作成功!</div>
                    </div>
                </div>
            )
        }

        let footerButton;
        if (this.state.currentStep == 0) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large"
                        onClick={this.next}>下一步</Button>
                </div>
            )
        } else if (this.state.currentStep == 1) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" onClick={this.prev}
                        style={{ marginRight: 20 }} >上一步</Button>
                    <Button type="primary" size="large" onClick={this.next}
                        style={{ marginRight: 20 }} >下一步</Button>
                </div>
            )
        } else if (this.state.currentStep == 2) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" onClick={this.prev}
                        style={{ marginRight: 20 }} >上一步</Button>
                    <Button type="primary" size="large" loading={this.state.confirmLoading}
                        onClick={this.handleAddClick.bind(this)}>提交</Button>
                </div>
            )
        } else if (this.state.currentStep == 3) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                </div>
            )
        }




        return (
            <Drawer
                bodyStyle={{ paddingBottom: 80 }}
                width={800}
                title={'新增计划'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    {drawerContent}
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        );
    }
}
const AddInspectPlanForm = Form.create()(addInspectPlanForm);


class schoolPatrolConditionManager extends Component {
    constructor(props) {
        super(props);
        var date = new Date();
        var year = date.getFullYear();
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            // searchTextRealame: '',
            data: [],
            filterDate: [year + '-01-01', year + '-12-31'],
            columnData: []
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let startDate = moment().subtract(6, 'days').format('YYYY-MM-DD')
        let endDate = moment().format('YYYY-MM-DD')
        checkConditionBySchoolApi(parseInt(sessionStorage.getItem("departmentId")), startDate, endDate, undefined)
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    columnData.push({
                        key: index + 1,
                        symbol: item.symbol,
                        people: item.realName,
                        date: item.createDate,
                        timePeriod: item.createTime,
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
                //console.log(columnData);
                // if (columnData.length != 0) {
                //     this.setState({
                //         columnData: columnData,
                //         tableLoading: false,
                //         filterDate: [columnData[columnData.length - 1].date, columnData[0].date],
                //     });
                // } else {
                //     this.setState({
                //         columnData: columnData,
                //         tableLoading: false
                //     });
                // }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            if (values.deadline == undefined && values.patrolPeople == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true
                });
                let startDate = null;
                let endDate = null;
                if (values.deadline != undefined) {
                    startDate = moment(values.deadline[0]).format('YYYY-MM-DD');
                    endDate = moment(values.deadline[1]).format('YYYY-MM-DD');
                }
                let columnData = [];
                checkConditionBySchoolApi(parseInt(sessionStorage.getItem("departmentId")), startDate, endDate, values.patrolPeople)
                    .then((res) => {
                        res.data.forEach((item, index) => {
                            //console.log("getAllUser", item);
                            columnData.push({
                                key: index + 1,
                                symbol: item.symbol,
                                people: item.realName,
                                date: item.createDate,
                                timePeriod: item.createTime,
                            });
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false
                        });
                        //console.log(columnData);
                        // if (columnData.length != 0) {
                        //     this.setState({
                        //         columnData: columnData,
                        //         tableLoading: false,
                        //         filterDate: [columnData[columnData.length - 1].date, columnData[0].date],
                        //     });
                        // } else {
                        //     this.setState({
                        //         columnData: columnData,
                        //         tableLoading: false
                        //     });
                        // }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });


            }
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }


    drawGraph() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.drawPunchCardGraphFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                values.period[0].format('YYYY-MM-DD');
                console.log(values);
                dataForDrawPunchCardApi(values)
                    .then((res) => {
                        this.setState({
                            confirmLoading: false
                        })
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            } else {
                this.setState({
                    msg: '图表相关数据获取失败！',
                    alertVisible: true,
                    confirmLoading: false
                });
            }
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        this.setState({
            // searchTextRealname: selectedKeys[0],
            filterDate: [selectedKeys[0].pre, selectedKeys[0].after]
        });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        let { columnData } = this.state;
        this.setState({
            // searchTextRealname: '',
            filterDate: [columnData[columnData.length - 1].date, columnData[0].date],
        });
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
        })
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const dateFormat = 'YYYY-MM-DD';
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        },
        {
            title: "日期",
            dataIndex: "date",
            key: "date",
            sorter: (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
            sortOrder: sortedInfo.columnKey === 'date' && sortedInfo.order,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => {
                return (
                    <div className="custom-filter-dropdown">
                        <RangePicker
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0] ?
                                [moment(selectedKeys[0].pre, dateFormat), moment(selectedKeys[0].after, dateFormat)]
                                :
                                [moment(this.state.filterDate[0], dateFormat), moment(this.state.filterDate[1], dateFormat)]
                            }
                            format={dateFormat}
                            onChange={(date, dateString) =>
                                setSelectedKeys(dateString.length == 0 ? [] : [{
                                    pre: dateString[0],
                                    after: dateString[1]
                                }])
                            }
                        />
                        <Button style={{ marginLeft: '10px' }} type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>筛选</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                )
            },
            filterIcon: filtered => <Icon type="calendar" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => {
                if (new Date(record.date).getTime() >= new Date(value.pre).getTime() &&
                    new Date(record.date).getTime() <= new Date(value.after).getTime()) {
                    return true;
                } else {
                    return false;
                }

            },
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        },
        {
            title: "巡更时间段",
            dataIndex: "timePeriod",
            key: "timePeriod",
        },
        {
            title: "巡更人员",
            dataIndex: "people",
            key: "people",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => { setSelectedKeys(e.target.value ? [e.target.value] : []) }}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.people.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }];

        const { getFieldDecorator } = this.props.form;
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={11}>
                            <FormItem
                                label="日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem
                                label="巡更人员"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("patrolPeople", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入巡更人员"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    expandedRowRender={(record) => {
                        return (
                            <PunchCardInnerTable
                                onRef={this.onRef}
                                symbol={record.symbol}
                                that={this} />)
                    }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    onChange={this.handleChange}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </div>
        )
    }
}

class PunchCardInnerTable extends Component {
    constructor(props) {
        super(props);
        const innerColumns = [{
            title: '巡更时间',
            dataIndex: 'time',
            key: 'time',
            width: '30%',
        }, {
            title: '巡更地址',
            dataIndex: 'address',
            key: 'address',
            width: '70%',
        }];

        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            symbol: props.symbol,
            innerColumns: innerColumns,
            that: props.that
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        punchCardDetialBySymbolApi(parseInt(sessionStorage.getItem("departmentId")), this.state.symbol)
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    innerData.push({
                        time: item.createTime,
                        address: item.checkPointAddress,
                    });
                });
                this.setState({
                    innerData: innerData,
                    tableLoading: false
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }


    render() {
        return (
            <Table
                columns={this.state.innerColumns}
                dataSource={this.state.innerData}
                pagination={false}
                size='small'
                loading={this.state.tableLoading}
                locale={{ emptyText: '暂无数据' }}
                bordered={true}
                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
            />
        )
    }
}

//--------------------------------------------------------------------

class schoolInspectConditionManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            //detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            // searchText: '',
            // allCategory: [],
            // allStatus: []
            isSearch: false,
            classNameArr: [],
            existCategory: [],
            searchData: [],
            filteredInfo2: null,
            sortedInfo2: null,
            // searchText2: '',

            detailVisible: false,
            detailExist: false,

            searchChartLoading: true,
            chartInspectSearchData: {}
        };

    }

    componentDidMount() {
        this.refreshData();
    }

    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
            ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
            ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        // this.setState({
        //     tableLoading: true
        // });
        let columnData = [];
        let classNameArr = [];
        //let statusData = [];
        inspectPlanClassBySchoolIdApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    columnData.push({
                        key: index + 1,
                        teamId: item.classId,
                        teamName: item.name,
                        classmates: item.username,
                    });
                    classNameArr.push(item.name);
                    //statusData.push(item.statusString);
                });
                this.setState({
                    columnData: columnData,
                    classNameArr: classNameArr,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        // let existCategory=[];
        getExistCategoryBySchoolIdAip(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                // res.data.forEach((item, index) => {
                //     //console.log("getAllUser", item);
                //     existCategory.push({
                //         categoryId: item.categoryId,
                //         categoryName: item.categoryName,
                //     });
                //     //statusData.push(item.statusString);
                // });
                this.setState({
                    existCategory: res.data,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        this.getInspectInfo();
            
    }

    getInspectInfo = () => {
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            if (values.address == undefined && (values.categoryId == undefined || values.categoryId.length == 0) && (values.deadline == undefined || values.deadline.length == 0)
                && values.doneResult == undefined && values.doneStatus == undefined && values.teamName == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true
                });
                if (values.categoryId !== undefined && values.categoryId.length == 0) {
                    values.categoryId = undefined;
                }
                let searchData = [];
                getInspectPlanSearchApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then(res => {
                        res.data.forEach((item, index) => {
                            let inspectPlanIds = item.inspectplanIds;
                            let items = item.items;
                            let singlePlanNormalArr = item.singlePlanNormal;
                            let statusArr = item.statusInt;

                            //若部分完成且第一个未完成，则将第一个完成的放在最前面
                            if (item.status == 'half' && statusArr[0] == 2) {
                                for (let i = 1; i < statusArr.length; i++) {
                                    if (statusArr[i] == 1) {
                                        let tempInspectPlanIds = inspectPlanIds[0];
                                        let tempItems = items[0];
                                        let tempSinglePlanNormalArr = singlePlanNormalArr[0];
                                        let tempStatusArr = statusArr[0];

                                        inspectPlanIds[0] = inspectPlanIds[i];
                                        items[0] = items[i];
                                        singlePlanNormalArr[0] = singlePlanNormalArr[i];
                                        statusArr[0] = statusArr[i];

                                        inspectPlanIds[i] = tempInspectPlanIds;
                                        items[i] = tempItems;
                                        singlePlanNormalArr[i] = tempSinglePlanNormalArr;
                                        statusArr[i] = tempStatusArr;

                                        break;
                                    }
                                }
                            }

                            searchData.push({
                                key: index + 1,
                                teamId: item.classId,
                                teamName: item.className,
                                classmates: item.classMates,
                                createTime: item.createTime,
                                deadline: item.deadline,
                                address: item.address,
                                categoryId: item.categoryId,
                                categoryName: item.category,
                                doneStatus: item.status,
                                checkpointId: item.checkPointId,
                                inspectPlanIds: inspectPlanIds,
                                items: items,
                                statusArr: statusArr,
                                singlePlanNormalArr: singlePlanNormalArr,
                                normal: item.normal,
                            });
                            //statusData.push(item.statusString);
                        });
                        this.setState({
                            isSearch: true,
                            searchData: searchData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

                getInspectSearchChartDataApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then(res => {
                        let chartInspectSearchData = {
                            date: [],
                            doneNumber: [],
                        };
                        res.data.forEach((item, index) => {
                            chartInspectSearchData.date.push(item.date);
                            chartInspectSearchData.doneNumber.push(item.doneNumber);
                        });

                        this.setState({
                            searchChartLoading: false,
                            chartInspectSearchData: chartInspectSearchData,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        });
    }

    searchSubmit = (e) => {
        e.preventDefault();
        this.getInspectInfo();
    }

    showDetailDrawer(inspectPlanIds, items, statusArr, singlePlanNormalArr) {
        this.setState({
            detailExist: true,
            detailVisible: true,
            currentInspectPlanIds: inspectPlanIds,
            currentItems: items,
            currentStatusArr: statusArr,
            currentSinglePlanNormalArr: singlePlanNormalArr,
        })
    }

    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
        })
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    clearAll2 = () => {
        this.setState({
            filteredInfo2: null,
            sortedInfo2: null,
        });

    }

    handleChange2 = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo2: filters,
            sortedInfo2: sorter,
        });
    }

    handleSearch2 = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     // searchText2: selectedKeys[0],
        // });
    }

    handleSearchReset2 = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     // searchText2: '',
        // });
    }

    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        // this.setState({
        //     isSeagetElementByIdrch: false,
        // })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }


    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        },
        {
            title: "班次名称",
            dataIndex: "teamName",
            key: "teamName",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.teamName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        },
        {
            title: "成员",
            dataIndex: "classmates",
            key: "classmates",
        }];

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo2, filteredInfo2 } = this.state;
        sortedInfo2 = sortedInfo2 || {};
        filteredInfo2 = filteredInfo2 || {};


        let keyWidth = undefined;
        let teamWidth = undefined;
        let classmatesWidth = undefined;
        let deadlineWidth = undefined;
        let createTimeWidth = undefined;
        let categoryNameWidth = undefined;
        let doneStatusWidth = undefined;
        let actionWidth = undefined;
        let addressWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth){
            winWidth = window.innerWidth;
            console.log("width", winWidth)}
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth <= 1536) {
            keyWidth = 60;
            teamWidth = 120;
            classmatesWidth = 100;
            createTimeWidth = 120;
            deadlineWidth = 120;
            addressWidth = 150;
            categoryNameWidth = 110;
            doneStatusWidth = 110;
            actionWidth = 110;
            
        }

        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "班次名称",
            dataIndex: "teamName",
            key: "teamName",
            width: teamWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch2(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch2(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset2(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.teamName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "成员",
            dataIndex: "classmates",
            key: "classmates",
            width: classmatesWidth
        }, {
            title: '巡检日期',
            dataIndex: 'createTime',
            key: 'createTime',
            width: createTimeWidth,
            sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
            sortOrder: sortedInfo2.columnKey === 'createTime' && sortedInfo2.order,
        }, {
            title: '截止日期',
            dataIndex: 'deadline',
            key: 'deadline',
            width: deadlineWidth,
            sorter: (a, b) => new Date(a.deadline).getTime() - new Date(b.deadline).getTime(),
            sortOrder: sortedInfo2.columnKey === 'deadline' && sortedInfo2.order,
        }, {
            title: '排查点地址',
            dataIndex: 'address',
            key: 'address',
            width: addressWidth,
        }, {
            title: '排查类别',
            dataIndex: 'categoryName',
            key: 'categoryName',
            width: categoryNameWidth,
        }, {
            title: '完成情况',
            dataIndex: 'doneStatus',
            key: 'doneStatus',
            width: doneStatusWidth,
            render: (text, record) => {
                let normal;
                if (record.normal == 0) {
                    normal = (<div></div>)
                } else if (record.normal == 1) {
                    normal = (<Tag color={'green'}>一切正常</Tag>)
                } else if (record.normal == 2) {
                    normal = (<Tag color={'blue'}>异常已处理</Tag>)
                } else if (record.normal == 3) {
                    normal = (<Tag color={'red'}>有异常</Tag>)
                }

                if (text == 'done') {
                    return (<div><Tag color={'green'}>全部完成</Tag>{normal}</div>)
                } else if (text == 'half') {
                    return (<div><Tag color={'orange'}>部分完成</Tag>{normal}</div>)
                } else if (text == 'none') {
                    return (<div><Tag color={'red'}>未完成</Tag>{normal}</div>)
                }
            },
        }, {
            title: "操作详情",
            key: "action",
            width: actionWidth,
            render: (text, record) => {
                if (record.doneStatus == 'done' || record.doneStatus == 'half') {
                    return (
                        <span>
                            <a
                                href="javascript:;"
                                onClick={this.showDetailDrawer.bind(this, record.inspectPlanIds,
                                    record.items, record.statusArr, record.singlePlanNormalArr)}>
                                查看详情
                            </a>
                        </span>
                    )
                } else {
                    return (<span>&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;</span>)
                }
            }
        }];

        let categoryOptions;
        if (this.state.existCategory.length != 0) {
            categoryOptions = this.state.existCategory.map((d, index) =>
                <Option value={d.id} key={index}>{d.category}</Option>
            );
        }

        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="班次名称"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("teamName", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.classNameArr}
                                        placeholder="请输入班次名称"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), 'YYYY-MM-DD'),
                                        moment(this.getBeforeDayTime(), 'YYYY-MM-DD'),
                                    ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="排查类别"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("categoryId", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择排查类别(可多选)">
                                        {categoryOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="排查点地址"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("address", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入排查点地址"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="完成情况"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("doneStatus", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择完成情况">
                                        <Option value="全部完成">全部完成</Option>
                                        <Option value="部分完成">部分完成</Option>
                                        <Option value="未完成">未完成</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="完成结果"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("doneResult", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择完成结果">
                                        <Option value="一切正常">一切正常</Option>
                                        <Option value="异常已处理">异常已处理</Option>
                                        <Option value="有异常">有异常</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                {this.state.isSearch ? (
                    <div>
                        <div style={{
                            marginBottom: 16,
                            padding: 16,
                            width: '100%',
                            height: 300,
                            border: '1px solid',
                            borderColor: '#f5f5f5'
                        }}>
                            <Skeleton loading={this.state.searchChartLoading} active>
                                <ChartInspectSearch
                                    that={this}
                                    chartData={this.state.chartInspectSearchData} />
                            </Skeleton>
                        </div>
                        <Table
                            dataSource={this.state.searchData}
                            columns={columnsSearch}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            onChange={this.handleChange2}
                            rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                            pagination={{  //分页
                                total: this.state.searchData.length, //数据总数量
                                defaultPageSize: 10, //默认显示几条一页
                                //pageSize: 10,
                                showTotal: function (total) {  //设置显示一共几条数据
                                    return '共 ' + total + ' 条数据';
                                },
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSizeOptions: [5, 10, 20, 30]
                            }} />
                    </div>
                ) : (
                    <Table
                        dataSource={this.state.columnData}
                        columns={columns}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange}
                        expandedRowRender={(record) => {
                            return (
                                <InspectConditionInnerTable
                                    //wrappedComponentRef={(inst) => this.teammateTableFormRef = inst}
                                    //ref="teammateTableRefresh"
                                    onRef={this.onRef}
                                    teamId={record.teamId}
                                    that={this} />)
                        }}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.data.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                )}
                {
                    this.state.detailExist ? (
                        <InspectConditionDetail
                            visible={this.state.detailVisible}
                            currentInspectPlanIds={this.state.currentInspectPlanIds}
                            currentItems={this.state.currentItems}
                            currentStatusArr={this.state.currentStatusArr}
                            currentSinglePlanNormalArr={this.state.currentSinglePlanNormalArr}
                            that={this} />
                    ) : null
                }

                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={'每日巡检完成情况展示图'}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />

                </Modal>
            </div>
        )
    }
}
const SchoolInspectConditionManager = Form.create()(schoolInspectConditionManager);

class ChartInspectSearch extends Component {
    constructor(props) {
        super(props);

        this.state = {
            chartData: props.chartData,
            that: props.that,
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.chartData) != JSON.stringify(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that,
            }, () => {
                this.drawChart();
            })
        }
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartInspectSearch'));

            let dataZoom;
            if (this.state.chartData.date.length <= 30) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    start: (this.state.chartData.date.length - 30) / this.state.chartData.date.length * 100,
                    end: 100,
                }, {
                    start: (this.state.chartData.date.length - 30) / this.state.chartData.date.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }


            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['完成计划']
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        // restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                console.log(this.state)
                                this.state.that.setFullScreen(opts);

                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.date,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '数量',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '完成计划',
                    type: 'line',
                    data: this.state.chartData.doneNumber,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                    itemStyle: {
                        color: 'rgb(255, 70, 131)'
                    },
                    areaStyle: {
                        normal: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgb(255, 158, 68)' // 0% 处的颜色
                                }, {
                                    offset: 1, color: 'rgb(255, 70, 131)' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            },
                        }

                    },
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartInspectSearch' style={chartStyle} />)
    }
}

class InspectConditionInnerTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            filteredInfo: null,
            sortedInfo: null,
            tableLoading: true,
            teamId: props.teamId,
            that: props.that,
            innerData: [],
            detailVisible: false,
            detailExist: false,
            isMore: true,
        }
    }

    componentDidMount() {
        this.refreshData();
        this.props.onRef(this);
    }

    refreshData() {
        this.lookCurrent();
    }

    showDetailDrawer(inspectPlanIds, items, statusArr, singlePlanNormalArr) {
        this.setState({
            detailExist: true,
            detailVisible: true,
            currentInspectPlanIds: inspectPlanIds,
            currentItems: items,
            currentStatusArr: statusArr,
            currentSinglePlanNormalArr: singlePlanNormalArr,
        })
    }

    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
        })
    }

    lookCurrent = () => {
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        inspectPlanByClassIdApi(
            parseInt(sessionStorage.getItem("departmentId")), this.state.teamId, !this.state.isMore)
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    let inspectPlanIds = item.inspectplanIds;
                    let items = item.items;
                    let singlePlanNormalArr = item.singlePlanNormal;
                    let statusArr = item.statusInt;

                    //若部分完成且第一个未完成，则将第一个完成的放在最前面
                    if (item.status == 'half' && statusArr[0] == 2) {
                        for (let i = 1; i < statusArr.length; i++) {
                            if (statusArr[i] == 1) {
                                let tempInspectPlanIds = inspectPlanIds[0];
                                let tempItems = items[0];
                                let tempSinglePlanNormalArr = singlePlanNormalArr[0];
                                let tempStatusArr = statusArr[0];

                                inspectPlanIds[0] = inspectPlanIds[i];
                                items[0] = items[i];
                                singlePlanNormalArr[0] = singlePlanNormalArr[i];
                                statusArr[0] = statusArr[i];

                                inspectPlanIds[i] = tempInspectPlanIds;
                                items[i] = tempItems;
                                singlePlanNormalArr[i] = tempSinglePlanNormalArr;
                                statusArr[i] = tempStatusArr;

                                break;
                            }
                        }
                    }

                    innerData.push({
                        key: index + 1,
                        deadline: item.deadline,
                        checkpointId: item.checkPointId,
                        address: item.address,
                        categoryId: item.categoryId,
                        categoryName: item.category,
                        doneStatus: item.status,
                        inspectPlanIds: inspectPlanIds,
                        items: items,
                        statusArr: statusArr,
                        singlePlanNormalArr: singlePlanNormalArr,
                        rowSpanDeadline: 0,
                        rowSpanCheckpoint: 0,
                        normal: item.normal,
                    });
                });
                //为了表格的列合并
                let countDeadline = 1;
                for (let i = innerData.length - 1; i >= 0; i--) {
                    if (i == 0) {
                        innerData[i].rowSpanDeadline = countDeadline;
                        break;
                    }
                    if (innerData[i].deadline == innerData[i - 1].deadline) {
                        countDeadline++;
                    } else {
                        innerData[i].rowSpanDeadline = countDeadline;
                        countDeadline = 1;
                    }
                }

                let countCheckpoint = 1;
                for (let i = innerData.length - 1; i >= 0; i--) {
                    if (i == 0) {
                        innerData[i].rowSpanCheckpoint = countCheckpoint;
                        break;
                    }

                    if (innerData[i].deadline != innerData[i - 1].deadline) {
                        innerData[i].rowSpanCheckpoint = countCheckpoint;
                        countCheckpoint = 1;
                    } else if (innerData[i].checkpointId == innerData[i - 1].checkpointId) {
                        countCheckpoint++;
                    } else {
                        innerData[i].rowSpanCheckpoint = countCheckpoint;
                        countCheckpoint = 1;
                    }
                }
                this.setState({
                    innerData: innerData,
                    tableLoading: false,
                    isMore: false,
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    lookMore = () => {
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        inspectPlanByClassIdApi(
            parseInt(sessionStorage.getItem("departmentId")), this.state.teamId, !this.state.isMore)
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    let inspectPlanIds = item.inspectplanIds;
                    let items = item.items;
                    let singlePlanNormalArr = item.singlePlanNormal;
                    let statusArr = item.statusInt;

                    //若部分完成且第一个未完成，则将第一个完成的放在最前面
                    if (item.status == 'half' && statusArr[0] == 2) {
                        for (let i = 1; i < statusArr.length; i++) {
                            if (statusArr[i] == 1) {
                                let tempInspectPlanIds = inspectPlanIds[0];
                                let tempItems = items[0];
                                let tempSinglePlanNormalArr = singlePlanNormalArr[0];
                                let tempStatusArr = statusArr[0];

                                inspectPlanIds[0] = inspectPlanIds[i];
                                items[0] = items[i];
                                singlePlanNormalArr[0] = singlePlanNormalArr[i];
                                statusArr[0] = statusArr[i];

                                inspectPlanIds[i] = tempInspectPlanIds;
                                items[i] = tempItems;
                                singlePlanNormalArr[i] = tempSinglePlanNormalArr;
                                statusArr[i] = tempStatusArr;

                                break;
                            }
                        }
                    }

                    innerData.push({
                        key: index + 1,
                        deadline: item.deadline,
                        checkpointId: item.checkPointId,
                        address: item.address,
                        categoryId: item.categoryId,
                        categoryName: item.category,
                        doneStatus: item.status,
                        inspectPlanIds: inspectPlanIds,
                        items: items,
                        statusArr: statusArr,
                        singlePlanNormalArr: singlePlanNormalArr,
                        rowSpanDeadline: 0,
                        rowSpanCheckpoint: 0,
                        normal: item.normal,
                    });
                });
                //为了表格的列合并
                let countDeadline = 1;
                for (let i = innerData.length - 1; i >= 0; i--) {
                    if (i == 0) {
                        innerData[i].rowSpanDeadline = countDeadline;
                        break;
                    }
                    if (innerData[i].deadline == innerData[i - 1].deadline) {
                        countDeadline++;
                    } else {
                        innerData[i].rowSpanDeadline = countDeadline;
                        countDeadline = 1;
                    }
                }

                let countCheckpoint = 1;
                for (let i = innerData.length - 1; i >= 0; i--) {
                    if (i == 0) {
                        innerData[i].rowSpanCheckpoint = countCheckpoint;
                        break;
                    }

                    if (innerData[i].deadline != innerData[i - 1].deadline) {
                        innerData[i].rowSpanCheckpoint = countCheckpoint;
                        countCheckpoint = 1;
                    } else if (innerData[i].checkpointId == innerData[i - 1].checkpointId) {
                        countCheckpoint++;
                    } else {
                        innerData[i].rowSpanCheckpoint = countCheckpoint;
                        countCheckpoint = 1;
                    }
                }
                this.setState({
                    innerData: innerData,
                    tableLoading: false,
                    isMore: true,
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        const innerColumns = [{
            title: '截止日期',
            dataIndex: 'deadline',
            key: 'deadline',
            width: '20%',
            className: 'tableHeadColumn',
            sorter: (a, b) => new Date(a.deadline).getTime() - new Date(b.deadline).getTime(),
            sortOrder: sortedInfo.columnKey === 'deadline' && sortedInfo.order,
            render: (text, record, index) => {
                const obj = {
                    children: text,
                    props: {},
                };
                obj.props.rowSpan = record.rowSpanDeadline;
                return obj;
            },
        }, {
            title: '排查点地址',
            dataIndex: 'address',
            key: 'address',
            width: '25%',
            render: (text, record, index) => {
                const obj = {
                    children: text,
                    props: {},
                };
                obj.props.rowSpan = record.rowSpanCheckpoint;
                return obj;
            },
        }, {
            title: '排查类别',
            dataIndex: 'categoryName',
            key: 'categoryName',
            width: '20%',
        }, {
            title: '完成情况',
            dataIndex: 'doneStatus',
            key: 'doneStatus',
            width: '20%',
            render: (text, record) => {
                let normal;
                if (record.normal == 0) {
                    normal = (<div></div>)
                } else if (record.normal == 1) {
                    normal = (<Tag color={'green'}>一切正常</Tag>)
                } else if (record.normal == 2) {
                    normal = (<Tag color={'blue'}>异常已处理</Tag>)
                } else if (record.normal == 3) {
                    normal = (<Tag color={'red'}>有异常</Tag>)
                }


                if (text == 'done') {
                    return (<div><Tag color={'green'}>全部完成</Tag>{normal}</div>)
                } else if (text == 'half') {
                    return (<div><Tag color={'orange'}>部分完成</Tag>{normal}</div>)
                } else if (text == 'none') {
                    return (<div><Tag color={'red'}>未完成</Tag>{normal}</div>)
                }
            },
        }, {
            title: "操作详情",
            key: "action",
            width: '15%',
            render: (text, record) => {
                if (record.doneStatus == 'done' || record.doneStatus == 'half') {
                    return (
                        <span>
                            <a
                                href="javascript:;"
                                onClick={this.showDetailDrawer.bind(this, record.inspectPlanIds,
                                    record.items, record.statusArr, record.singlePlanNormalArr)}>
                                查看详情
                            </a>
                        </span>
                    )
                } else {
                    return (<span>&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;</span>)
                }
            }
        }];

        let title = (
            <div
                style={{
                    textAlign: 'center',
                }}>
                {this.state.isMore ?
                    (
                        <a
                            href="javascript:;"
                            onClick={this.lookCurrent.bind(this)}>
                            <Button><Icon type="minus-square" />查看最近</Button>

                        </a>
                    ) : null}
            </div>
        )

        let footer = (
            <div
                style={{
                    textAlign: 'center',
                }}>
                {this.state.isMore ?
                    (
                        <a
                            href="javascript:;"
                            onClick={this.lookCurrent.bind(this)}>
                            <Button><Icon type="minus-square" />查看最近</Button>

                        </a>
                    ) :
                    (
                        <a
                            href="javascript:;"
                            onClick={this.lookMore.bind(this)}>
                            <Button><Icon type="plus-square" />查看更多</Button>
                        </a>
                    )}
            </div>
        )

        return (
            <div>
                <Table
                    columns={innerColumns}
                    dataSource={this.state.innerData}
                    pagination={false}
                    onChange={this.handleChange}
                    size='small'
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    bordered={true}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    title={() => title}
                    footer={() => footer}
                />
                {
                    this.state.detailExist ? (
                        <InspectConditionDetail
                            visible={this.state.detailVisible}
                            currentInspectPlanIds={this.state.currentInspectPlanIds}
                            currentItems={this.state.currentItems}
                            currentStatusArr={this.state.currentStatusArr}
                            currentSinglePlanNormalArr={this.state.currentSinglePlanNormalArr}
                            that={this} />
                    ) : null
                }

            </div>
        )
    }
}

class InspectConditionDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentInspectPlanIds: props.currentInspectPlanIds,
            currentItems: props.currentItems,
            currentStatusArr: props.currentStatusArr,
            currentSinglePlanNormalArr: props.currentSinglePlanNormalArr,
            visible: props.visible,
            that: props.that,

            data: [],
            confirmLoading: false,

            previewVisible: false,
            previewImage: '',

            currentCategory: '',
            currentInspectItem: '',
            currentCategoryPicUrl: '',
            currentCreateTime: '',
            currentCreateUserName: '',
            currentActiveKey: props.currentInspectPlanIds[0] + '',

            activeKey: [], //控制list是否可展开

        };
        //console.log('currentInspectPlanIds', props.currentInspectPlanIds)
    }

    componentDidMount() {
        this.refreshData(this.state.currentInspectPlanIds[0]);
    }

    componentWillReceiveProps(props) {
        this.setState({
            currentInspectPlanIds: props.currentInspectPlanIds,
            currentItems: props.currentItems,
            currentStatusArr: props.currentStatusArr,
            currentSinglePlanNormalArr: props.currentSinglePlanNormalArr,
            visible: props.visible,
            that: props.that,
            currentActiveKey: props.currentInspectPlanIds[0] + '',
        });
        if (props.visible) {
            this.refreshData(props.currentInspectPlanIds[0]);
        }
    }

    refreshData(currentInspectPlanId) {
        this.setState({
            confirmLoading: true,
        })
        inspectDealDetailByInspectPlanIdApi(currentInspectPlanId)
            .then((res) => {
                if (JSON.stringify(res.data) != '{}') {
                    this.setState({
                        currentCategory: res.data.category,
                        currentInspectItem: res.data.inspectItem,
                        currentCategoryPicUrl: res.data.picUrl,
                        currentCreateTime: res.data.createTime,
                        currentCreateUserName: res.data.createUserName,
                        data: res.data.Info,
                    });
                }

                let activeKey = [];
                for (let i = 0; i < res.data.Info.length; i++) {
                    if (res.data.Info[i].statusString == '不通过') {
                        //this.state.activeKey.push(i + '');
                        // let activeKeyTemp = this.state.activeKey;
                        activeKey.push(i + '');
                    }
                }
                this.setState({
                    activeKey: activeKey,
                    confirmLoading: false,
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    tabsOnChange = (key) => {
        console.log('key', key);
        this.setState({
            currentActiveKey: key + ''
        })
        this.refreshData(parseInt(key));
    }

    handlePreview = (src) => {
        this.setState({
            previewImage: src,
            previewVisible: true,
        });
    }

    handlePreviewCancel = () => this.setState({ previewVisible: false })


    render() {
        if (this.state.currentInspectPlanIds == undefined) {
            return (<div></div>)
        }

        const Panel = Collapse.Panel;
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            position: 'relative'
        };

        const panels = this.state.data.map((d, index) => {
            let status;
            if (d.statusString == '通过') {
                status = 3;
            } else if (d.statusString == '不通过') {
                status = 4;
            } else if (d.statusString == '已处理') {
                status = 5;
            }

            let header = (
                <div style={{ height: '100%', width: '100%' }}>
                    <div style={{ width: '80%', left: 0 }}>
                        {d.content}
                    </div>
                    <img
                        style={{
                            width: '15%',
                            right: 5,
                            top: 0,
                            bottom: 0,
                            margin: 'auto',
                            position: 'absolute',
                        }}
                        alt="计划状态"
                        src={require('../img/status' + status + '.png')}
                    />
                </div>
            );

            let photos;
            if (d.photo == '') {
                photos = (
                    <Card.Grid
                        key={0}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt="暂无图片"
                            src={require('../img/nophoto.png')} />
                    </Card.Grid>
                );
            } else {
                photos = d.photoArray.map((d2, index2) =>
                    <Card.Grid
                        key={index2}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt={status == 4 ? '巡检现场照片' : '异常处理照片'}
                            src={UrlPrefix + d2}
                            onClick={this.handlePreview.bind(this, UrlPrefix + d2)} />
                    </Card.Grid>
                );
            }

            let recordContent;
            if (d.recordContent == null) {
                recordContent = '无';
            } else {
                recordContent = d.recordContent;
            }

            let listTiele = ['', ''];
            if (status == 4) {
                listTiele[0] = '巡检记录';
                listTiele[1] = '巡检现场照片';
            } else if (status == 5) {
                listTiele[0] = '异常处理记录';
                listTiele[1] = '异常处理照片';
            }
            let listData = [{
                title: listTiele[0],
                description: recordContent,
            }, {
                title: listTiele[1],
                description: (
                    <Card
                        hoverable
                        style={{ marginTop: '10px' }}>
                        {photos}
                    </Card>
                ),
            }];

            if (d.updateUserName != null) {
                listData.unshift({
                    title: '注',
                    description: (
                        <span>
                            本巡检项由
                            <span style={{ color: 'red' }}>
                                {' ' + d.updateUserName + ' '}
                            </span>
                            于
                            <span style={{ color: 'red' }}>
                                {' ' + d.modifyTime + ' '}
                            </span>
                            更新巡检结果信息
                        </span>
                    ),
                });
            }
            return (
                <Panel header={header} key={index + ''} disabled={(status == 3) ? true : false} >
                    <List
                        itemLayout="horizontal"
                        dataSource={listData}
                        renderItem={item => (
                            <List.Item>
                                <List.Item.Meta
                                    title={item.title}
                                    description={item.description}
                                />
                            </List.Item>
                        )}
                    />
                </Panel>
            );
        })

        const tabPanes = this.state.currentInspectPlanIds.map((d, index) => {

            let alt;
            let src;
            if (this.state.currentSinglePlanNormalArr[index] == 1) {
                alt = '全部通过';
                src = 'pass';
            } else if (this.state.currentSinglePlanNormalArr[index] == 2) {
                alt = '异常已处理';
                src = 'dealicon';
            } else if (this.state.currentSinglePlanNormalArr[index] == 3) {
                alt = '有异常';
                src = 'alert';
            }

            let tab = (
                <div>
                    {this.state.currentItems[index]}
                    {this.state.currentSinglePlanNormalArr[index] == 0 ? null : (
                        <img
                            style={{
                                width: 20,
                                height: 20,
                                marginLeft: 10,
                                marginTop: -3,
                            }}
                            alt={alt}
                            src={require('../img/' + src + '.png')} />
                    )}

                </div>
            )

            return (
                <TabPane
                    tab={tab}
                    key={d + ''}
                    disabled={this.state.currentStatusArr[index] == 2 ? true : false} >
                    <Skeleton loading={this.state.confirmLoading} active>
                        <Collapse
                            defaultActiveKey={this.state.activeKey}
                            onChange={key => this.setState({ activeKey: key })} >
                            {panels}
                        </Collapse>
                        <Alert
                            style={{ marginTop: 12 }}
                            message="提交时间"
                            description={this.state.currentCreateTime}
                            type="info"
                            showIcon
                        />
                    </Skeleton>
                </TabPane>
            )
        }

        );

        return (
            <div>
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={800}
                    title='巡检结果详情'
                    visible={this.state.visible}
                    onClose={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                    destroyOnClose={true}
                    closable
                >
                    <Tabs
                        defaultActiveKey={this.state.currentInspectPlanIds[0] + ''}
                        activeKey={this.state.currentActiveKey}
                        onChange={this.tabsOnChange}>
                        {tabPanes}
                    </Tabs>
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                </Drawer>
                <Modal
                    destroyOnClose
                    visible={this.state.previewVisible}
                    footer={null}
                    bodyStyle={{
                        paddingTop: 48,
                    }}
                    onCancel={this.handlePreviewCancel}>
                    <img
                        alt="照片"
                        style={{ width: '100%' }}
                        src={this.state.previewImage} />
                </Modal>
            </div>

        );
    }
}



//--------------------------------------------------------------
class schoolSafetySceneManager extends Component {//安全现场
    constructor(props) {
        super(props);
        this.state = {
            updateVisible: false,
            detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            // searchTextAddress: '',
            // searchTextReporter: '',
            allCategory: [],
            allStatus: [],

            isSearch: false,
            realNameArr: [], //上报人的autocomplete数据
            existCategory: [],
            searchData: [],

            searchChartLoading: true,
            chartSafetySceneSearchData: {}
        };

    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let statusData = [];
        safetysceneBySchoolApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                if(res.data) {
                    res.data.forEach((item, index) => {
                        columnData.push({
                            key: index + 1,
                            id: item.id,
                            safetyLevel: item.safetyLevel,
                            address: item.address,
                            reporterId: item.reporter,
                            reporterName: item.reportName,
                            status: item.statusString,
                            createTime: item.createTime,
                            modifyTime: item.modifyTime,
                            categoryId: item.categoryId,
                            categoryName: item.categoryName,
                            dealName: item.dealName
                        });
                        statusData.push(item.statusString);
                    });
                }
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                    preData: columnData
                });
                let statusDataUnique = statusData.filter(function (element, index, array) {
                    return array.indexOf(element) === index;
                });
                let allStatus = statusDataUnique.map((d, index) => {
                    return ({
                        text: d,
                        value: d,
                    })
                })
                this.setState({
                    allStatus: allStatus,
                });
                
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        allInspectItemCategory(parseInt(sessionStorage.getItem("departmentId")), 4)
            .then((res) => {
                //console.log(res.data);
                let categories = [];
                res.data.forEach((item, index) => {
                    let temp = {
                        text: item.category,
                        value: item.category,
                    }
                    categories.push(temp);
                });
                this.setState({
                    allCategory: categories,
                })
            }).catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getExistCategoryBySchoolIdAip(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    existCategory: res.data,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        allUserApi(4, sessionStorage.getItem("departmentId"))
            .then((res) => {
                let realNameArr = [];
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    if(item.realName != "") {
                        realNameArr.push(item.realName);
                    }
                });
                this.setState({
                    realNameArr: realNameArr
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //点击表格中 修改 触发的操作
    showUpdateModal(id, safetyLevel, address, reporterName,
        createTime, categoryId, category) {
        let level = "";
        switch (safetyLevel) {
        case 0: level = "非常安全"; break;
        case 1: level = "安全"; break;
        case 2: level = "一般"; break;
        case 3: level = "危险"; break;
        case 4: level = "非常危险"; break;
        }
        this.setState({
            updateVisible: true,
            currentId: id,
            currentSafetyLevel: level,
            currentAddress: address,
            currentReporterName: reporterName,
            currentCreateTime: createTime,
            currentCategoryId: categoryId,
            currentCategoryName: category
        })
    }

    formatTime(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();
        return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
    }

    formatNumber(n) {
        n = n.toString();
        return n[1] ? n : '0' + n;
    }

    //修改巡逻计划 点击提交按钮后的操作
    updateHandleClick(id) {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.updateSafetysceneFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                let reporter = sessionStorage.getItem("userId");
                forwardSafetyScene(id, reporter, values.categoryId, this.state.currentCategoryName)
                    .then((res) => {
                        if (res.data.res == "success") {
                            this.setState({
                                updateVisible: false,
                                confirmLoading: false
                            });

                            getAccessTokenForSendMsg()
                                .then((res) => {
                                    let accessToken = res.data.access_token
                                    getChargeManWeChatId(values.categoryId, sessionStorage.getItem("departmentId"))
                                        .then((res) => {
                                            let unbind = [];
                                            let content = "";
                                            for (let i = 0; i < res.data.length; i++) {
                                                if (res.data[i].res == "success") {
                                                    let toUser = res.data[i].msg;
                                                    let dateTime = this.formatTime(new Date());
                                                    if (content == "") {
                                                        safetysceneDetailByIdApi(id)
                                                            .then((res) => {
                                                                content = res.data.content;
                                                                sendMessage(accessToken, toUser, this.state.currentCategoryName, content, sessionStorage.getItem("username"), dateTime)
                                                                    .then(() => {
                                                                        //do nothing
                                                                    })
                                                                    .catch((e) => {
                                                                        if (e.response) {
                                                                            //请求已发出，服务器返回状态码不是2xx。
                                                                            console.info(e.response.data)
                                                                            console.info(e.response.status)
                                                                            console.info(e.response.headers)
                                                                        } else if (e.request) {
                                                                            // 请求已发出，但没有收到响应
                                                                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                                                                            // 在node中是一个http.ClientRequest实例
                                                                            console.info(e.request)
                                                                        } else {
                                                                            //发送请求时异常，捕捉到错误
                                                                            console.info('error', e.message)
                                                                        }
                                                                        console.info(e.config)
                                                                    })
                                                            })
                                                            .catch((e) => {
                                                                if (e.response) {
                                                                    //请求已发出，服务器返回状态码不是2xx。
                                                                    console.info(e.response.data)
                                                                    console.info(e.response.status)
                                                                    console.info(e.response.headers)
                                                                } else if (e.request) {
                                                                    // 请求已发出，但没有收到响应
                                                                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                                                                    // 在node中是一个http.ClientRequest实例
                                                                    console.info(e.request)
                                                                } else {
                                                                    //发送请求时异常，捕捉到错误
                                                                    console.info('error', e.message)
                                                                }
                                                                console.info(e.config)
                                                            });
                                                    } else {
                                                        sendMessage(accessToken, toUser, this.state.currentCategoryName, content, sessionStorage.getItem("username"), dateTime)
                                                            .then((res) => {
                                                                //do nothing
                                                            })
                                                            .catch((e) => {
                                                                if (e.response) {
                                                                    //请求已发出，服务器返回状态码不是2xx。
                                                                    console.info(e.response.data)
                                                                    console.info(e.response.status)
                                                                    console.info(e.response.headers)
                                                                } else if (e.request) {
                                                                    // 请求已发出，但没有收到响应
                                                                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                                                                    // 在node中是一个http.ClientRequest实例
                                                                    console.info(e.request)
                                                                } else {
                                                                    //发送请求时异常，捕捉到错误
                                                                    console.info('error', e.message)
                                                                }
                                                                console.info(e.config)
                                                            })
                                                    }
                                                }
                                                else {
                                                    unbind.push(res.data[i].msg)
                                                }
                                            }
                                            if (unbind.length != 0) {
                                                let msg = unbind.join("、") + "主管未绑定服务号";
                                                message.error(msg);
                                            } else {
                                                message.success("转发成功!");
                                            }
                                        })
                                        .catch((e) => {
                                            if (e.response) {
                                                //请求已发出，服务器返回状态码不是2xx。
                                                console.info(e.response.data)
                                                console.info(e.response.status)
                                                console.info(e.response.headers)
                                            } else if (e.request) {
                                                // 请求已发出，但没有收到响应
                                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                                // 在node中是一个http.ClientRequest实例
                                                console.info(e.request)
                                            } else {
                                                //发送请求时异常，捕捉到错误
                                                console.info('error', e.message)
                                            }
                                            console.info(e.config)
                                        })
                                })
                                .catch((e) => {
                                    if (e.response) {
                                        //请求已发出，服务器返回状态码不是2xx。
                                        console.info(e.response.data)
                                        console.info(e.response.status)
                                        console.info(e.response.headers)
                                    } else if (e.request) {
                                        // 请求已发出，但没有收到响应
                                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                                        // 在node中是一个http.ClientRequest实例
                                        console.info(e.request)
                                    } else {
                                        //发送请求时异常，捕捉到错误
                                        console.info('error', e.message)
                                    }
                                    console.info(e.config)
                                })

                            this.refreshData();
                            val.resetFields();
                        } else if (res.data.res == "fail") {
                            console.log('fail');
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    })
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    showDetailModal(id, safetyLevel, address, reporterName, status,
        createTime, modifyTime, categoryName) {
        let level = "";
        switch (safetyLevel) {
        case 1: level = "安全"; break;
        case 2: level = "一般"; break;
        case 3: level = "危险"; break;
        case 4: level = "非常危险"; break;
        case 5: level = "巡检排查"; break;
        }
        this.setState({
            detailVisible: true,
            currentId: id,
            currentSafetyLevel: level,
            currentAddress: address,
            currentReporterName: reporterName,
            currentStatus: status,
            currentCreateTime: createTime,
            currentModifyTime: modifyTime,
            currentCategoryName: categoryName,
        })
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }
    //关闭模态框
    handleUpdateCancel() {
        let val = this.refs.updateSafetysceneFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            updateVisible: false,
        });
    }
    //关闭模态框
    handleDetailCancel() {
        this.setState({
            alertVisible: false,
            detailVisible: false,
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchTextAddress: selectedKeys[0],
        //     searchTextReporter: selectedKeys[0]
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchTextAddress: '',
        //     searchTextReporter: '',
        // });
    }

    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            if (values.address == undefined && values.categoryId == undefined && values.safetyLevel == undefined
                && values.reporterName == undefined && values.status == undefined && values.createTime == undefined
                && values.modifyTime == undefined && values.dealName == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true,
                    isSearch: true,
                });

                if (values.categoryId !== undefined && values.categoryId.length == 0) {
                    values.categoryId = undefined;
                }

                if (values.safetyLevel !== undefined && values.safetyLevel.length == 0) {
                    values.safetyLevel = undefined;
                }

                if (values.createTime == undefined || values.createTime.length == 0) {
                    values.reportStartDate = undefined;
                    values.reportEndDate = undefined;
                } else {
                    values.reportStartDate = moment(values.createTime[0]).format('YYYY-MM-DD');
                    values.reportEndDate = moment(values.createTime[1]).format('YYYY-MM-DD');
                }

                if (values.modifyTime == undefined || values.modifyTime.length == 0) {
                    values.dealStartDate = undefined;
                    values.dealEndDate = undefined;
                } else {
                    values.dealStartDate = moment(values.modifyTime[0]).format('YYYY-MM-DD');
                    values.dealEndDate = moment(values.modifyTime[1]).format('YYYY-MM-DD');
                }

                let columnData = [];
                getSafetySceneSearchApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        res.data.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                id: item.id,
                                safetyLevel: item.safetyLevel,
                                address: item.address,
                                reporterId: item.reporter,
                                reporterName: item.reportName,
                                status: item.statusString,
                                createTime: item.createTime,
                                modifyTime: item.modifyTime,
                                categoryId: item.categoryId,
                                categoryName: item.categoryName,
                                dealName: item.dealName
                            });
                        });

                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

                getSafetySceneSearchChartDataApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then(res => {
                        //console.log(res.data);
                        this.setState({
                            searchChartLoading: false,
                            chartSafetySceneSearchData: res.data,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // ��node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        });
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
            columnData: this.state.preData,
        })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        let keyWidth = undefined;
        let categoryNameWidth = undefined;
        let reporterNameWidth = undefined;
        let statusWidth = undefined;
        let actionWidth = undefined;
        let timeWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            categoryNameWidth = 110;
            reporterNameWidth = 90;
            statusWidth = 80;
            actionWidth = 110;
            timeWidth = 120;
        }

        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "地址",
            dataIndex: "address",
            key: "address",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.address.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "项目类别",
            dataIndex: "categoryName",
            key: "categoryName",
            width: categoryNameWidth,
            filters: this.state.allCategory,
            filteredValue: filteredInfo.categoryName || null,
            onFilter: (value, record) => record.categoryName.includes(value),
            filterIcon: filtered =>
                <Icon
                    type="filter"
                    style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
        }, {
            title: "安全等级",
            dataIndex: "safetyLevel",
            key: "safetyLevel",
            sorter: (a, b) => a.safetyLevel - b.safetyLevel,
            sortOrder: sortedInfo.columnKey === 'safetyLevel' && sortedInfo.order,
            render: (text) => (
                <div style={{ width: '90px' }}>
                    <img
                        style={{ width: '100%' }}
                        src={require('../img/safetyLevel' + text + '.png')} />
                </div>
            )
        }, {
            title: "上报人",
            dataIndex: "reporterName",
            key: "reporterName",
            width: reporterNameWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.reporterName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "状态",
            dataIndex: "status",
            key: "status",
            width: statusWidth,
            filters: this.state.allStatus,
            filteredValue: filteredInfo.status || null,
            onFilter: (value, record) => record.status.includes(value),
            filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            render: (text) => {
                if (text == '已处理') { return (<span style={{ color: 'green' }}>已处理</span>) }
                else if (text == '未处理') { return (<span style={{ color: 'red' }}>未处理</span>) }
                else if (text == '处理中') { return (<span style={{ color: '#096dd9' }}>处理中</span>) }
            },
        }, {
            title: "上报时间",
            dataIndex: "createTime",
            key: "createTime",
            width: timeWidth,
            sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
            sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order,
        }, {
            title: "处理时间",
            dataIndex: "modifyTime",
            key: "modifyTime",
            width: timeWidth,
            sorter: (a, b) => new Date(a.modifyTime).getTime() - new Date(b.modifyTime).getTime(),
            sortOrder: sortedInfo.columnKey === 'modifyTime' && sortedInfo.order,
            render: (text, record) => {
                if (record.status == '已处理') { return (<span>{text}</span>) }
                else if (record.status == '未处理') { return (<span>-</span>) }
            },
        }, {
            title: "处理人",
            dataIndex: "dealName",
            key: "dealName",
            width: reporterNameWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.reporterName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            },
            render: (text, record) => {
                if (record.status == '未处理') { return (<span>-</span>) }
                else {
                    return (<span>{text}</span>)
                }
            }
        }, {
            title: "操作详情",
            key: "action",
            width: actionWidth,
            render: (text, record) => {

                if (record.status == '已处理') {
                    return (
                        <span>
                            &nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;
                            <Divider type="vertical" />
                            <a href="javascript:;" onClick={this.showDetailModal.bind(this,
                                record.id, record.safetyLevel, record.address,
                                record.reporterName, record.status, record.createTime,
                                record.modifyTime, record.categoryName)}>详细</a>
                        </span>
                    )
                } else if (record.status == '未处理' || record.status == '处理中') {
                    return (
                        <span>
                            <a href="javascript:;" onClick={this.showUpdateModal.bind(this,
                                record.id, record.safetyLevel, record.address,
                                record.reporterName, record.createTime, record.categoryId, record.categoryName)}>修改</a>
                            <Divider type="vertical" />
                            <a href="javascript:;" onClick={this.showDetailModal.bind(this,
                                record.id, record.safetyLevel, record.address,
                                record.reporterName, record.status, record.createTime,
                                record.modifyTime, record.categoryName)}>详细</a>
                        </span>
                    )
                }
            }
        }];

        let categoryOptions;
        if (this.state.existCategory.length != 0) {
            categoryOptions = this.state.existCategory.map((d, index) =>
                <Option value={d.id} key={index}>{d.category}</Option>
            );
        }

        let statusOptions;
        if (this.state.allStatus.length != 0) {
            statusOptions = this.state.allStatus.map((d, index) =>
                <Option value={d.value} key={index}>{d.value}</Option>
            );
        }

        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="地址"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("address", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入地址"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="项目类别"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("categoryId", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择项目类别(可多选)">
                                        {categoryOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="安全等级"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("safetyLevel", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择安全等级(可多选)">
                                        <Option value={1}>安全</Option>
                                        <Option value={2}>一般</Option>
                                        <Option value={3}>危险</Option>
                                        <Option value={4}>非常危险</Option>
                                        <Option value={5}>巡检排查</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="上报人"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("reporterName", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.realNameArr}
                                        placeholder="请输入上报人"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="上报时间"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("createTime", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="处理时间"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("modifyTime", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="处理人"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("dealName", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.realNameArr}
                                        placeholder="请输入处理人"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="状态"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("status", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择状态">
                                        {statusOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                {this.state.isSearch ? (
                    <div style={{
                        marginBottom: 16,
                        padding: 16,
                        width: '100%',
                        height: 300,
                        border: '1px solid',
                        borderColor: '#f5f5f5'
                    }}>
                        <Skeleton loading={this.state.searchChartLoading} active>
                            <ChartSafetySceneSearch
                                that={this}
                                chartData={this.state.chartSafetySceneSearchData}/>
                        </Skeleton>
                    </div>
                ) : null}
                {/* <Button style={{ marginBottom: '20px' }} onClick={this.clearAll}>
                    <Icon type="delete" theme="outlined" />清除筛选与排序</Button> */}
                <Modal
                    title={"修改项目类别"}
                    visible={this.state.updateVisible}
                    onCancel={this.handleUpdateCancel.bind(this)}
                    destroyOnClose
                    closable
                    footer={[
                        <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                            onClick={this.updateHandleClick.bind(this, this.state.currentId)}>提交</Button>
                    ]}
                >
                    <UpdateSafetysceneForm ref="updateSafetysceneFormValue"
                        currentSafetyLevel={this.state.currentSafetyLevel} currentAddress={this.state.currentAddress}
                        currentReporterName={this.state.currentReporterName} currentCreateTime={this.state.currentCreateTime}
                        currentCategoryId={this.state.currentCategoryId} />
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Modal>
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={600}
                    title={'安全现场详细信息'}
                    visible={this.state.detailVisible}
                    onClose={this.handleDetailCancel.bind(this)}
                    destroyOnClose={true}
                    closable
                >
                    <SafetysceneDetail
                        currentId={this.state.currentId} currentSafetyLevel={this.state.currentSafetyLevel}
                        currentAddress={this.state.currentAddress} currentReporterName={this.state.currentReporterName}
                        currentStatus={this.state.currentStatus} currentCreateTime={this.state.currentCreateTime}
                        currentModifyTime={this.state.currentModifyTime} currentCategoryName={this.state.currentCategoryName} />
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                            onClick={this.handleDetailCancel.bind(this)}>关闭</Button>
                    </div>
                </Drawer>

                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    onChange={this.handleChange}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />

                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={'每日隐患上报/处理情况展示图'}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />

                </Modal>
            </div>
        )
    }
}
const SchoolSafetySceneManager = Form.create()(schoolSafetySceneManager);

class ChartSafetySceneSearch extends Component {
    constructor(props) {
        super(props);

        this.state = {
            chartData: props.chartData,
            that: props.that,
            
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.chartData) !== JSON.stringify(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that,
            }, () => {
                this.drawChart();
            })
        }
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            //console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartSafetySceneSearch'));
            let i = 0;
            let dataZoom;
            if (this.state.chartData.date.length <= 30) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {    
                //统计中间一片有数据的大致区间（百分比），避免时间线太长，在初始化时让数据位于中间
                let dataStart = 0, num = this.state.chartData.date.length, dataEnd = num - 1;
                //将数据从前往后遍历，找到第一个有上报数的日期，并计算该点处在总数据的百分比位置
                for (; dataStart < num; dataStart++) { 
                    if (this.state.chartData.reportNum[dataStart] == 1) { 
                        break;
                    }
                }
                //因为计算出来的区间百分比会是小数，-5和下方的+5适当增加区间范围
                let dataStartPercent = dataStart * 100 / num - 5;
                //将数据从后往前遍历，找到第一个有上报数或处理数的日期，并计算该点处在总数据的百分比位置
                for (; dataEnd > dataStart; dataEnd--) { 
                    if (this.state.chartData.reportNum[dataEnd] == 1 || this.state.chartData.dealNum[dataEnd] == 1) { 
                        break;
                    }
                }
                let dataEndPercent = dataEnd * 100 / num + 5;

                dataZoom = [{
                    type: 'inside',
                    start: parseInt(dataStartPercent),
                    end: parseInt(dataEndPercent),
                }, {
                    start: (this.state.chartData.date.length - 30) / this.state.chartData.date.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }


            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['上报数', '处理数']
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        // restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                console.log(this.state)
                                this.state.that.setFullScreen(opts);

                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.date,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '数量',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '上报数',
                    type: 'line',
                    data: this.state.chartData.reportNum,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                }, {
                    name: '处理数',
                    type: 'line',
                    data: this.state.chartData.dealNum,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartSafetySceneSearch' style={chartStyle} />)
    }
}

class updateSafetysceneForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentSafetyLevel: props.currentSafetyLevel,
            currentAddress: props.currentAddress,
            currentReporterName: props.currentReporterName,
            currentCreateTime: props.currentCreateTime,
            currentCategoryId: props.currentCategoryId,
            allCategoryOptions: [],
        };
    }

    componentDidMount() {
        let allCategoryOptions = [];
        allInspectItemCategory(parseInt(sessionStorage.getItem("departmentId")), 4)
            .then((res) => {
                res.data.forEach((item, index) => {
                    allCategoryOptions.push({
                        value: item.categoryId,
                        text: item.category
                    });
                });

                this.setState({
                    allCategoryOptions: allCategoryOptions
                })

            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        }

        const options = this.state.allCategoryOptions.map((d, index) => <Option value={d.value} key={index}>{d.text}</Option>);
        //console.log(1, this.state.currentAddress);
        return (
            <Form>
                <FormItem
                    label='现场地址'
                    {...formItemLayout}>
                    {getFieldDecorator("address", {
                        initialValue: this.state.currentAddress,
                        rules: [{
                            required: false,
                            message: "请输入现场地址!"
                        }]
                    })(
                        <Input
                            size="large"
                            disabled={true}
                        ></Input>
                    )}
                </FormItem>
                <FormItem
                    label='安全等级'
                    {...formItemLayout}>
                    {getFieldDecorator("safetyLevel", {
                        initialValue: this.state.currentSafetyLevel,
                        rules: [{
                            required: false,
                            message: "请输入安全等级!"
                        }]
                    })(
                        <Input
                            size="large"
                            disabled={true}
                        ></Input>
                    )}
                </FormItem>
                <FormItem
                    label='上报人'
                    {...formItemLayout}>
                    {getFieldDecorator("reporter", {
                        initialValue: this.state.currentReporterName,
                        rules: [{
                            required: false,
                            message: "请输入上报人!"
                        }]
                    })(
                        <Input
                            size="large"
                            disabled={true}
                        ></Input>
                    )}
                </FormItem>
                <FormItem
                    label='上报时间'
                    {...formItemLayout}>
                    {getFieldDecorator("createTime", {
                        initialValue: this.state.currentCreateTime,
                        rules: [{
                            required: false,
                            message: "请输入上报时间!"
                        }]
                    })(
                        <Input
                            size="large"
                            disabled={true}
                        ></Input>
                    )}
                </FormItem>
                <FormItem
                    label='上报类别'
                    {...formItemLayout}>
                    {getFieldDecorator("categoryId", {
                        initialValue: this.state.currentCategoryId,
                        rules: [{
                            required: true,
                            message: "请选择上报类别!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="选择上报类别">
                            {options}
                        </Select>
                    )}
                </FormItem>
            </Form>
        );
    }
}
const UpdateSafetysceneForm = Form.create()(updateSafetysceneForm);

class SafetysceneDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentId: props.currentId,
            currentSafetyLevel: props.currentSafetyLevel,
            currentAddress: props.currentAddress,
            currentReporterName: props.currentReporterName,
            currentStatus: props.currentStatus,
            currentCreateTime: props.currentCreateTime,
            currentModifyTime: props.currentModifyTime,
            currentCategoryName: props.currentCategoryName,

            currentContent: '',
            currentPhoto: [],
            currentVideo: '',
            currentPhotoStr: '',
            currentDealContent: '',
            currentDealPhoto: [],
            currentDealVideo: '',
            currentDealPhotoStr: '',
            currentDealUserName: '',
            currentEvaluate: 0,

            previewVisible: false,
            previewImage: '',
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        //console.log(this.state);
        safetysceneDetailByIdApi(this.state.currentId)
            .then((res) => {
                //console.log(res);
                if (this.state.currentStatus == '已处理') {
                    this.setState({
                        currentContent: res.data.content,
                        currentPhoto: res.data.photoList,
                        currentVideo: res.data.video,
                        currentDealContent: res.data.dealContent,
                        currentDealPhoto: res.data.dealPhotoList,
                        currentDealVideo: res.data.dealVideo,
                        currentDealUserName: res.data.realName,
                        currentEvaluate: res.data.evaluate,
                        currentPhotoStr: res.data.photo,
                        currentDealPhotoStr: res.data.dealPhoto
                    });
                } else if (this.state.currentStatus == '未处理') {
                    this.setState({
                        currentContent: res.data.content,
                        currentPhoto: res.data.photoList,
                        currentVideo: res.data.video,
                        currentPhotoStr: res.data.photo,
                    });
                } else if (this.state.currentStatus == '处理中') {
                    this.setState({
                        currentContent: res.data.content,
                        currentPhoto: res.data.photoList,
                        // currentDealContent: res.data.dealContent,
                        // currentDealPhoto: res.data.dealPhotoList,
                        currentDealUserName: res.data.realName,

                        currentPhotoStr: res.data.photo,
                        currentDealPhotoStr: res.data.dealPhoto
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }


    handlePreview = (src) => {
        this.setState({
            previewImage: src,
            previewVisible: true,
        });
    }
    //查看video
    handlePreview2 = (src) => {

    }

    //图片旋转测试
    
    handleCancel = () => this.setState({ previewVisible: false })

    render() {
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            padding: '10px',
            position: 'relative'
        };

        let prePhotos;
        let preVideo;
        if (this.state.currentPhotoStr == '') {
            prePhotos = (
                <Card.Grid
                    key={0}
                    style={gridStyle}>
                    <img
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            margin: 'auto',
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        alt="上报照片"
                        src={require('../img/nophoto.png')} />
                </Card.Grid>
            );
        } else {
            prePhotos = this.state.currentPhoto.map((d, index) =>
                <Card.Grid
                    key={index}
                    style={gridStyle}>
                    {/* <RViewerJS> */}
                        
                    <img
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            margin: 'auto',
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        alt="上报照片"
                        src={UrlPrefix + d}
                    />
                    {/* </RViewerJS> */}
                   
                </Card.Grid>
            );
        }
        preVideo = (
            <Card.Grid
                key={0}
                style={gridStyle}>
                <video
                    style={{
                        width: 'auto',
                        height: 'auto',
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        margin: 'auto',
                        maxWidth: '100%',
                        maxHeight: '100%',
                        padding: 5,
                    }}
                    src={UrlPrefix + this.state.currentVideo} controls />
            </Card.Grid>
        );
        let preData = [{
            title: '上报地址',
            description: this.state.currentAddress,
        }, {
            title: '上报类别',
            description: this.state.currentCategoryName,
        }, {
            title: '安全等级',
            description: this.state.currentSafetyLevel,
        }, {
            title: '上报人',
            description: this.state.currentReporterName,
        }, {
            title: '状态',
            description: this.state.currentStatus,
        }, {
            title: '上报时间',
            description: this.state.currentCreateTime,
        }, {
            title: '上报内容',
            description: this.state.currentContent,
        }, {
            title: '上报照片',
            description: (
                <Card
                    hoverable
                    style={{ marginTop: '10px' }}>
                    <RViewerJS>
                        {prePhotos}
                    </RViewerJS>
                    
                </Card>),
        }, {
            title: '上报视频',
            description: (
                this.state.currentVideo == "" ?
                    <span>暂无视频</span>
                    :
                    <Card
                        hoverable
                        style={{ marginTop: '10px' }}>
                        <RViewerJS>
                            {preVideo}
                        </RViewerJS>
                    </Card>
            ),
        }];

        let dealData;
        if (this.state.currentStatus == '已处理' || this.state.currentStatus == '处理中') {
            let dealPhotos;
            if (this.state.currentDealPhotoStr == '') {
                dealPhotos = (
                    <Card.Grid
                        key={0}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt="暂无图片"
                            src={require('../img/nophoto.png')} />
                    </Card.Grid>
                );
            } else {
                dealPhotos = this.state.currentDealPhoto.map((d, index) =>
                    <Card.Grid
                        key={index}
                        style={gridStyle}>
                        <RViewerJS >
                                
                            <img
                                style={{
                                    width: 'auto',
                                    height: 'auto',
                                    position: 'absolute',
                                    top: 0,
                                    left: 0,
                                    right: 0,
                                    bottom: 0,
                                    margin: 'auto',
                                    maxWidth: '100%',
                                    maxHeight: '100%',
                                    padding: 5,
                                }}
                                alt="上报照片"
                                src={UrlPrefix + d}
                            />
                        </RViewerJS>
                       
                    </Card.Grid>
                );
            }
            let dealVideo = (
                <Card.Grid
                    key={0}
                    style={gridStyle}>
                    <video
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            margin: 'auto',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        src={UrlPrefix + this.state.currentDealVideo} controls />
                </Card.Grid>
            );
            dealData = [{
                title: '处理时间',
                description: this.state.currentModifyTime,
            }, {
                title: '处理人员',
                description: this.state.currentDealUserName,
            }, {
                title: '处理内容',
                description: this.state.currentDealContent,
            }, {
                title: '处理照片',
                description: (
                    <Card
                        hoverable
                        style={{ marginTop: '10px' }}>
                        <RViewerJS>
                            {dealPhotos}
                        </RViewerJS>
                    </Card>),
            }, {
                title: '处理视频',
                description: (
                    this.state.currentDealVideo == "" ?
                        <span>暂无视频</span>
                        :
                        <Card
                            hoverable
                            style={{ marginTop: '10px' }}>
                            <RViewerJS>
                                {dealVideo}
                            </RViewerJS>
                        </Card>
                ),
            }]

            if (this.state.currentStatus === '已处理') {
                dealData.push({
                    title: '评价情况',
                    description: (
                        this.state.currentEvaluate === 0 ?
                            <span>暂未评价</span>
                            :
                            <Rate disabled defaultValue={this.state.currentEvaluate} />
                    )
                })
            }
        } else if (this.state.currentStatus == '未处理') {
            dealData = [{
                title: '此条暂未处理',
            }]
        }


        return (
            <div>
                <Tabs
                    defaultActiveKey="1">
                    <TabPane tab={<span ><IconFont type="icon-weiwancheng" className='iconTabs' />上报信息</span>} key="1">
                        <List
                            itemLayout="horizontal"
                            dataSource={preData}
                            renderItem={item => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={item.title}
                                        description={item.description}
                                    />
                                </List.Item>
                            )}
                        />
                    </TabPane>
                    <TabPane tab={<span><IconFont type="icon-yiwanchengdingdan" className='iconTabs' />处理信息</span>} key="2">
                        <List
                            itemLayout="horizontal"
                            dataSource={dealData}
                            renderItem={item => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={item.title}
                                        description={item.description}
                                    />
                                </List.Item>
                            )}
                        />
                    </TabPane>
                </Tabs>
                <Modal
                    destroyOnClose
                    visible={this.state.previewVisible}
                    footer={null}
                    bodyStyle={{
                        paddingTop: 48,
                    }}
                    onCancel={this.handleCancel}>
                    <RViewerJS>
                        <img
                            alt="安全现场上报与处理照片"
                            style={{ width: '100%' }}
                            src={this.state.previewImage} />
                    </RViewerJS>
                    
                </Modal>
            </div>

        );
    }
}



class PatrolCharts extends Component {
    constructor(props) {
        super(props);

        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            chartsNum: 4,
            doneChartsNum: 0,
            chartDataPatrolDay: {
                date: [],
                should: [],
                real: []
            },
            // chartDataInspectDay: {},
            // chartDataTroublePoint: [],
            // chartDataTroubleItem: [],
            chartDataPatrolAll: {
                monthList: [],
                chartData: [{
                    date: [],
                    real: [],
                    should: []
                }]
            },
            topChartDataToday: {
                should: 0,
                real: 0,
                safetySceneFound: 0,
                safetySceneDeal: 0,
                inspectReal: 0
            },
            topChartDataAll: {
                inspectReal: 0,
                patrolReal: 0,
                safetySceneFound: 0,
                safetySceneDeal: 0
            },
            modalTitle: '',
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            confirmLoading: true,
            doneChartsNum: 0,
        });
        getPatrolCountByDay(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let chartData = {
                    date: [],
                    should: [],
                    real: []
                };
                for (let key in res.data) {
                    chartData.date.push(key);
                    chartData.should.push(res.data[key].should)
                    chartData.real.push(res.data[key].real);
                }

                this.setState({
                    chartDataPatrolDay: chartData,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getPatrolCountAll(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    chartDataPatrolAll: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getTodayInfo(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    topChartDataToday: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getAllTimeInfo(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    topChartDataAll: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    setFullScreen(title, opts) {
        this.setState({
            fullScreenVisible: true,
            modalTitle: title
        })
        if (title == '巡更完成情况总览') {
            this.setState({
                calendarVisible: true,
            });
        } else {
            this.setState({
                fullVisible: true,
            });
            let fullchart = echarts.init(document.getElementById('fullScreen'))
            fullchart.setOption(opts);
        }

    }

    handleCancel() {
        this.setState({
            fullScreenVisible: false,
            calendarVisible: false,
            fullVisible: false,
        })
    }

    render() {
        let gridStyle = {
            marginBottom: 24,
        };

        let cellSize = [80, 80];
        let pieRadius = 30;
        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            cellSize = [55, 55];
            pieRadius = 24;
        }

        // console.log('JSON.stringify(this.state.chartDataPatrolAll)', JSON.stringify(this.state.chartDataPatrolAll))
        return (
            <div style={{ background: '#f0f2f5', margin: -24, }}>
                <Row gutter={24}>
                    <Col span={8}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(233, 217, 211)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/patrolToday.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            今日实巡
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.real}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(210, 208, 223)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/patrolPlan.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            计划巡更
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.should}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(207, 218, 213)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/patrolAll.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            累计巡更
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataAll.patrolReal}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                </Row>
                <Row gutter={24}>
                    <Col span={24}>
                        <Card
                            title={'巡更完成情况总览'}
                            style={gridStyle}
                            bodyStyle={{ height: 600, padding: 24 }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                {
                                    (JSON.stringify(this.state.chartDataPatrolAll) ==
                                        '{"monthList":[],"chartData":[{"date":[],"real":[],"should":[]}]}') ?
                                        (
                                            <Empty
                                                style={{
                                                    marginTop: 200,
                                                }} />
                                        ) :
                                        (
                                            <ChartCalendar
                                                chartData={this.state.chartDataPatrolAll}
                                                that={this}
                                                divId={'chartCalendar'}
                                                pieRadius={pieRadius}
                                                cellSize={cellSize}
                                                fullScreenShow={true} />
                                        )
                                }
                            </Skeleton>
                        </Card>
                    </Col>
                    {/* <Col span={24}>
                        <Card
                            title={'每日巡更次数统计'}
                            style={gridStyle}
                            bodyStyle={{ height: 400, padding: 24 }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                {
                                    (JSON.stringify(this.state.chartDataPatrolDay) == '{"date":[],"should":[],"real":[]}') ?
                                        (
                                            <Empty
                                                style={{
                                                    marginTop: 100,
                                                }} />
                                        ) :
                                        (
                                            <ChartPatrolDay
                                                chartData={this.state.chartDataPatrolDay}
                                                that={this} />
                                        )
                                }
                            </Skeleton>
                        </Card>
                    </Col> */}
                </Row>
                {/* <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={this.state.modalTitle}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.handleCancel() }}>
                    {this.state.fullVisible ?
                        (
                            <div id='fullScreen'
                                style={{
                                    width: '100%',
                                    height: '100%',
                                }} />
                        ) : undefined
                    }
                    {this.state.calendarVisible ?
                        (
                            <ChartCalendar
                                chartData={this.state.chartDataPatrolAll}
                                that={this}
                                divId={'calendarFullScreen'}
                                pieRadius={30}
                                cellSize={[80, 80]}
                                fullScreenShow={false}></ChartCalendar>
                        ) : undefined
                    }
                </Modal> */}
            </div>
        )
    }
}

class InspectCharts extends Component {
    constructor(props) {
        super(props);

        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            chartsNum: 5,
            doneChartsNum: 0,
            // chartDataPatrolDay: {},
            chartDataInspectDay: {
                date: [],
                times: []
            },
            chartDataTroublePoint: [],
            chartDataTroubleItem: [],
            // chartDataPatrolAll: {},
            topChartDataToday: {
                should: 0,
                real: 0,
                safetySceneFound: 0,
                safetySceneDeal: 0,
                inspectReal: 0
            },
            topChartDataAll: {
                inspectReal: 0,
                patrolReal: 0,
                safetySceneFound: 0,
                safetySceneDeal: 0
            },
            modalTitle: '',
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            confirmLoading: true,
            doneChartsNum: 0,
        });

        getInspectTimeByDay(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let chartData = {
                    date: [],
                    times: [],
                };
                res.data.forEach((item, index) => {
                    chartData.date.push(item.ymdDate);
                    chartData.times.push(item.times);
                });

                this.setState({
                    chartDataInspectDay: chartData,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getTroublePoint(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    chartDataTroublePoint: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getTroubleItem(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    chartDataTroubleItem: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getTodayInfo(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    topChartDataToday: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getAllTimeInfo(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    topChartDataAll: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    setFullScreen(title, opts) {
        this.setState({
            fullScreenVisible: true,
            modalTitle: title
        })
        this.setState({
            fullVisible: true,
        });
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    handleCancel() {
        this.setState({
            fullScreenVisible: false,
            calendarVisible: false,
            fullVisible: false,
        })
    }

    render() {
        let gridStyle = {
            marginBottom: 24,
        };

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            //
        }
        console.log('JSON.stringify(this.state.chartDataInspectDay)', JSON.stringify(this.state.chartDataInspectDay))
        return (
            <div style={{ background: '#f0f2f5', margin: -24, }}>
                <Row gutter={24}>
                    <Col span={8}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(233, 217, 211)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/inspectNum.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            <div dangerouslySetInnerHTML={{ __html: '今日巡检数/</br>累计巡检数' }} />
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.inspectReal + '/' + this.state.topChartDataAll.inspectReal}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(210, 208, 223)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/sceneReport.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            <div dangerouslySetInnerHTML={{ __html: '今日隐患上报数/</br>累计隐患上报数' }} />
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.safetySceneFound + '/' + this.state.topChartDataAll.safetySceneFound}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(207, 218, 213)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/sceneDeal.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            <div dangerouslySetInnerHTML={{ __html: '今日隐患处理数/</br>累计隐患处理数' }} />
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.safetySceneDeal + '/' + this.state.topChartDataAll.safetySceneDeal}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                </Row>
                <Row gutter={24}>
                    <Col span={16}>
                        <Row>
                            <Card
                                title={'每日巡检次数统计'}
                                style={gridStyle}
                                bodyStyle={{ height: 440, padding: 24 }}
                                bordered={false}>
                                <Skeleton loading={this.state.confirmLoading} active>
                                    {
                                        (JSON.stringify(this.state.chartDataInspectDay) == '{"date":[],"times":[]}') ?
                                            (
                                                <Empty
                                                    style={{
                                                        marginTop: 100,
                                                    }} />
                                            ) :
                                            (
                                                <ChartInspectDay
                                                    chartData={this.state.chartDataInspectDay}
                                                    that={this} />
                                            )
                                    }
                                </Skeleton>
                            </Card>
                        </Row>
                    </Col>
                    <Col span={8}>
                        <Row>
                            <Card
                                title={'巡检异常项目排名'}
                                style={gridStyle}
                                bodyStyle={{ height: 180, padding: 12 }}
                                bordered={false}>
                                <Skeleton loading={this.state.confirmLoading} active>
                                    <ChartTroubleItem
                                        chartData={this.state.chartDataTroubleItem} />
                                </Skeleton>
                            </Card>
                        </Row>
                        <Row>
                            <Card
                                title={'巡检异常地点排名'}
                                style={gridStyle}
                                bodyStyle={{ height: 180, padding: 12 }}
                                bordered={false}>
                                <Skeleton loading={this.state.confirmLoading} active>
                                    <ChartTroublePoint chartData={this.state.chartDataTroublePoint} />
                                </Skeleton>
                            </Card>
                        </Row>
                    </Col>
                </Row>
                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={this.state.modalTitle}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.handleCancel() }}>
                    {this.state.fullVisible ?
                        (
                            <div id='fullScreen'
                                style={{
                                    width: '100%',
                                    height: '100%',
                                }} />
                        ) : undefined
                    }
                </Modal>
            </div>
        )
    }
}

class ChartPatrolDay extends Component {
    constructor(props) {
        super(props);

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;

        this.state = {
            chartData: props.chartData,
            that: props.that,
            winWidth: winWidth
        };
    }

    componentDidMount() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartPatrolDay'));

            let dataZoom;

            if (this.state.chartData.date.length <= 7) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    start: (this.state.chartData.date.length - 7) / this.state.chartData.date.length * 100,
                    end: 100,
                }, {
                    start: (this.state.chartData.date.length - 7) / this.state.chartData.date.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }

            // if (this.state.winWidth < 1500) {
            //     chart.setOption({
            //         legend: {
            //             left: 50
            //         },
            //     })
            // }

            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['应巡', '实巡']
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        // restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                console.log(this.state)
                                this.state.that.setFullScreen('每日巡更次数统计', opts);

                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.date,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '次数',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '应巡',
                    type: 'line',
                    symbol: 'none',
                    smooth: true,
                    data: this.state.chartData.should,
                }, {
                    name: '实巡',
                    type: 'line',
                    symbol: 'none',
                    smooth: true,
                    data: this.state.chartData.real,
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartPatrolDay' style={chartStyle} />)
    }
}

class ChartInspectDay extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
            that: props.that,
        };
    }

    componentDidMount() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartInspectDay'));

            let dataZoom;

            if (this.state.chartData.date.length <= 7) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    start: (this.state.chartData.date.length - 7) / this.state.chartData.date.length * 100,
                    end: 100,
                }, {
                    start: (this.state.chartData.date.length - 7) / this.state.chartData.date.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }

            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                legend: {
                    data: ['巡检次数']
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        // restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                this.state.that.setFullScreen('每日巡检次数统计', opts);

                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    data: this.state.chartData.date,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '次数',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '巡检次数',
                    type: 'bar',
                    symbol: 'none',
                    smooth: true,
                    data: this.state.chartData.times,
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartInspectDay' style={chartStyle}></div>)
    }
}

class ChartDataVisitorDay extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
            that: props.that,
        };
    }

    componentDidMount() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartInspectDay'));

            let dataZoom;

            if (this.state.chartData.date.length <= 7) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    start: (this.state.chartData.date.length - 7) / this.state.chartData.date.length * 100,
                    end: 100,
                }, {
                    start: (this.state.chartData.date.length - 7) / this.state.chartData.date.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }

            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                legend: {
                    data: ['访客次数']
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        // restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                this.state.that.setFullScreen('每日访客次数统计', opts);

                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    data: this.state.chartData.date,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '次数',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '访客次数',
                    type: 'bar',
                    symbol: 'none',
                    smooth: true,
                    data: this.state.chartData.times,
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartInspectDay' style={chartStyle}></div>)
    }
}
class ChartTroublePoint extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
        };
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        let data = this.state.chartData;
        if (this.state.chartData.length > 4) {
            data = this.state.chartData.slice(0, 4);
        }
        return (
            <div id='chartTroublePoint' style={chartStyle}>
                <List
                    itemLayout="horizontal"
                    size='small'
                    dataSource={data}
                    renderItem={(item, index) => {
                        let backgroundColor;
                        let fontColor;
                        if (index < 3) {
                            backgroundColor = '#314659';
                            fontColor = '#fff';
                        } else {
                            backgroundColor = '#f5f5f5';
                            fontColor = 'rgba(0,0,0,.65)';
                        }

                        let firstPaddingTop;
                        if (index == 0) {
                            firstPaddingTop = 4;
                        } else {
                            firstPaddingTop = 8;
                        }
                        return (
                            <List.Item
                                style={{
                                    borderBottom: 0,
                                    paddingTop: firstPaddingTop,
                                }}>
                                <Avatar
                                    style={{
                                        backgroundColor: backgroundColor,
                                        verticalAlign: 'middle',
                                        color: fontColor,
                                        marginLeft: 12,
                                        marginTop: 1,
                                        fontSize: 12,
                                        lineHeight: '22px',
                                    }}
                                    size={20}>
                                    {index + 1}
                                </Avatar>
                                <span
                                    style={{
                                        marginLeft: 20,
                                        flex: '1 1',
                                        marginRight: 12,
                                        overflow: 'hidden',
                                        whiteSpace: 'nowrap',
                                        textOverflow: 'ellipsis',
                                        fontSize: 14,
                                        lineHeight: '22px',
                                        width: 100,
                                    }}>
                                    {item.address}
                                </span>
                                <span
                                    style={{
                                        marginRight: 24,
                                        fontSize: 14,
                                        lineHeight: '22px',
                                    }}>
                                    {item.times}
                                </span>
                            </List.Item>
                        )
                    }}
                />
            </div>
        )
    }
}

class ChartTroubleItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
        };
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        let data = this.state.chartData;
        if (this.state.chartData.length > 4) {
            data = this.state.chartData.slice(0, 4);
        }
        return (
            <div id='chartTroubleItem' style={chartStyle}>
                <List
                    itemLayout="horizontal"
                    size='small'
                    dataSource={data}
                    renderItem={(item, index) => {
                        let backgroundColor;
                        let fontColor;
                        if (index < 3) {
                            backgroundColor = '#314659';
                            fontColor = '#fff';
                        } else {
                            backgroundColor = '#f5f5f5';
                            fontColor = 'rgba(0,0,0,.65)';
                        }

                        let firstPaddingTop;
                        if (index == 0) {
                            firstPaddingTop = 4;
                        } else {
                            firstPaddingTop = 8;
                        }
                        return (
                            <List.Item
                                style={{
                                    borderBottom: 0,
                                    paddingTop: firstPaddingTop,
                                }}>
                                <Avatar
                                    style={{
                                        backgroundColor: backgroundColor,
                                        verticalAlign: 'middle',
                                        color: fontColor,
                                        marginLeft: 12,
                                        marginTop: 1,
                                        fontSize: 12,
                                        lineHeight: '22px',
                                    }}
                                    size={20}>
                                    {index + 1}
                                </Avatar>
                                <span
                                    style={{
                                        marginLeft: 20,
                                        flex: '1 1',
                                        marginRight: 12,
                                        overflow: 'hidden',
                                        whiteSpace: 'nowrap',
                                        textOverflow: 'ellipsis',
                                        fontSize: 14,
                                        lineHeight: '22px',
                                        width: 100,
                                    }}>
                                    {item.item}
                                </span>
                                <span
                                    style={{
                                        marginRight: 24,
                                        fontSize: 14,
                                        lineHeight: '22px',
                                    }}>
                                    {item.times}
                                </span>
                            </List.Item>
                        )
                    }}
                />
            </div>
        )
    }
}

class ChartCalendar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData.chartData || [],
            monthList: props.chartData.monthList || [],
            // chartData: [{
            //     date: ["2019-03-01", "2019-03-02", "2019-03-03", "2019-03-04", "2019-03-05", "2019-03-06", "2019-03-07", "2019-03-08", "2019-03-09", "2019-03-10",
            //         "2019-03-11", "2019-03-12", "2019-03-13", "2019-03-14", "2019-03-15", "2019-03-16", "2019-03-17", "2019-03-18", "2019-03-19", "2019-03-20",
            //         "2019-03-21", "2019-03-22", "2019-03-23", "2019-03-24", "2019-03-25", "2019-03-26", "2019-03-27", "2019-03-28", "2019-03-29", "2019-03-30", "2019-03-31"],
            //     real: [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
            //     should: [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
            // }, {
            //     date: ["2019-04-01", "2019-04-02", "2019-04-03", "2019-04-04", "2019-04-05", "2019-04-06", "2019-04-07", "2019-04-08", "2019-04-09", "2019-04-10",
            //         "2019-04-11", "2019-04-12", "2019-04-13", "2019-04-14", "2019-04-15", "2019-04-16", "2019-04-17", "2019-04-18", "2019-04-19", "2019-04-20",
            //         "2019-04-21", "2019-04-22", "2019-04-23", "2019-04-24", "2019-04-25", "2019-04-26"],
            //     real: [0, 2, 0, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 5, 5, 5, 1, 2, 3, 4, 5, 6],
            //     should: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]
            // }],
            // monthList: ["2019-03", "2019-04"],
            real: [],
            should: [],
            pieRadius: props.pieRadius,
            cellSize: props.cellSize,
            optionData: [],
            dayList: [],
            that: props.that,
            divId: props.divId,
            fullScreenShow: props.fullScreenShow,

        };
        console.log(props.chartData)
    }

    componentDidMount() {
        //test
        var dataList = [];
        var year = 0;
        var yearList = [];
        this.state.chartData.forEach((item) => {
            for (var l = 0; l < item.date.length; l++) {
                if (year != item.date[item.date.length - 1 - l].substring(0, 4)) {
                    console.log(year)
                    year = item.date[item.date.length - 1 - l].substring(0, 4);
                    yearList.push(year);
                }
            }
            for (var i = 0; i < item.date.length; i++) {

                let temp = [];
                temp.push(item.date[i]);
                temp.push(item.should[i] == 0 ? 0 : (item.real[i] / item.should[i]).toFixed(2) * 100);
                dataList.push(temp)
            }
        });
        console.log(yearList);
        console.log(dataList);
        // item.date.forEach((item2, index)=>{
        //     dataList.push({
        //         date:item2.date,
        //         rate:(item2.real/item.should)
        //     })
        // });
        // console.log(item);
        // {
        //     range: ['2011-01-01', '2011-12-31'], 
        //     cellSize: ['auto', 15],
        //     left: 70,
        //     right: 30,
        // },
        var calendarList = [];
        for (var i = 0; i < yearList.length && i < 3; i++) {
            calendarList.push({
                top: yearList.length == 1 ? 230 : 60 + 170 * i,
                range: yearList[yearList.length - 1 - i],
                cellSize: ['auto', 15],
                left: '12%',
                right: '6%',
                monthLabel: {
                    nameMap: 'cn'
                },
                dayLabel: {
                    //    ?
                    nameMap: 'cn'
                },
            })
        }
        // {
        //     type: 'heatmap',
        //     coordinateSystem: 'calendar',
        //     calendarIndex: 0,
        //     data: dataList
        // }
        var seriesList = [];
        for (var j = 0; j < yearList.length && j < 3; j++) {
            seriesList.push({
                type: 'heatmap',
                coordinateSystem: 'calendar',
                calendarIndex: j,
                data: dataList
            })
        }
        var text;
        if (yearList.length == 1) {
            text = yearList[0] + "年巡更完成率情况"
        }
        else {
            text = yearList[0] + "-" + yearList[yearList.length - 1] + "年巡更完成率情况"
        }
        console.log(text);
        console.log(calendarList);
        // function getVirtulData(year) {
        //     var data = 
        //     [
        //         ["2011-08-26", 4], ["2011-08-27", 3], ["2011-08-24", 6], ["2011-08-25", 4], ["2011-08-22", 4], ["2011-08-23", 5], ["2011-08-20", 3], ["2011-08-21", 2], ["2011-09-30", 4], ["2011-08-28", 4], ["2011-08-29", 4], ["2011-10-24", 4], ["2011-12-10", 11], ["2011-12-11", 3], ["2011-12-12", 4], ["2011-12-13", 6], ["2011-12-15", 4], ["2011-12-16", 10], ["2011-12-17", 10], ["2011-12-18", 9], ["2011-12-19", 7], ["2011-09-29", 3], ["2011-09-28", 5], ["2011-08-31", 4], ["2011-08-30", 3], ["2011-09-21", 6], ["2011-09-20", 6], ["2011-09-23", 1], ["2011-09-22", 2], ["2011-09-25", 2], ["2011-09-24", 5], ["2011-09-27", 3], ["2011-09-26", 2], ["2011-12-07", 4], ["2011-11-29", 6], ["2011-12-05", 3], ["2011-12-04", 9], ["2011-12-03", 1], ["2011-12-02", 4], ["2011-12-01", 2], ["2011-11-20", 4], ["2011-10-22", 3], ["2011-10-21", 9], ["2011-11-23", 8], ["2011-11-24", 5], ["2011-11-25", 4], ["2011-10-25", 3], ["2011-12-08", 6], ["2011-07-30", 1], ["2011-07-31", 1], ["2011-09-14", 3], ["2011-09-15", 2], ["2011-09-16", 5], ["2011-09-17", 4], ["2011-09-10", 1], ["2011-09-11", 4], ["2011-09-12", 1], ["2011-09-13", 16], ["2011-10-30", 4], ["2011-10-31", 1], ["2011-11-28", 6], ["2011-12-06", 3], ["2011-10-29", 6], ["2011-11-30", 5], ["2011-09-03", 7], ["2011-09-02", 7], ["2011-09-01", 6], ["2011-09-07", 3], ["2011-09-06", 3], ["2011-09-05", 2], ["2011-09-04", 13], ["2011-09-09", 4], ["2011-09-08", 4], ["2011-10-23", 4], ["2011-11-21", 5], ["2011-11-22", 5], ["2011-10-20", 8], ["2011-10-27", 8], ["2011-10-26", 2], ["2011-08-08", 3], ["2011-08-09", 2], ["2011-12-09", 1], ["2011-08-01", 4], ["2011-08-02", 2], ["2011-11-27", 3], ["2011-08-04", 1], ["2011-08-05", 3], ["2011-08-07", 2], ["2011-11-06", 3], ["2011-09-18", 5], ["2011-09-19", 7], ["2011-07-28", 2], ["2011-08-19", 4], ["2011-08-16", 3], ["2011-08-14", 4], ["2011-07-27", 2], ["2011-08-12", 2], ["2011-08-11", 2], ["2011-08-10", 1], ["2011-10-12", 1], ["2011-10-10", 5], ["2011-10-16", 2], ["2011-10-17", 6], ["2011-10-18", 5], ["2011-10-19", 5], ["2011-11-26", 4], ["2011-08-13", 1], ["2011-07-26", 3], ["2011-07-25", 1], ["2011-10-01", 3], ["2011-10-03", 1], ["2011-11-05", 2], ["2011-10-05", 1], ["2011-10-04", 2], ["2011-10-06", 1], ["2011-10-09", 8], ["2011-10-08", 8], ["2011-11-09", 5], ["2011-12-30", 3], ["2011-12-31", 3], ["2011-11-15", 6], ["2011-11-14", 8], ["2011-11-17", 4], ["2011-11-16", 3], ["2011-11-11", 8], ["2011-11-10", 7], ["2011-11-13", 4], ["2011-11-12", 5], ["2011-11-19", 8], ["2011-11-18", 7], ["2011-08-03", 2], ["2011-12-29", 3], ["2011-12-28", 2], ["2011-12-25", 4], ["2011-12-24", 4], ["2011-12-27", 2], ["2011-12-26", 3], ["2011-12-21", 3], ["2011-12-20", 6], ["2011-12-23", 2], ["2011-12-22", 7],
        //         ["2012-05-07", 6], ["2012-04-16", 4], ["2012-04-02", 4], ["2012-06-27", 3], ["2012-07-21", 4], ["2012-06-26", 2], ["2012-10-31", 1], ["2012-04-09", 6], ["2012-05-17", 3], ["2012-06-24", 1], ["2012-09-10", 1], ["2012-12-17", 2], ["2012-12-15", 4], ["2012-12-14", 3], ["2012-12-13", 3], ["2012-12-12", 3], ["2012-12-11", 1], ["2012-02-28", 3], ["2012-05-28", 6], ["2012-07-31", 5], ["2012-12-18", 1], ["2012-04-12", 4], ["2012-05-29", 2], ["2012-11-29", 2], ["2012-05-16", 2], ["2012-11-27", 2], ["2012-11-26", 2], ["2012-11-24", 3], ["2012-11-23", 1], ["2012-11-22", 2], ["2012-11-21", 3], ["2012-05-04", 3], ["2012-02-16", 5], ["2012-04-10", 5], ["2012-02-14", 4], ["2012-02-15", 4], ["2012-02-12", 4], ["2012-02-13", 4], ["2012-02-10", 5], ["2012-02-11", 4], ["2012-01-15", 4], ["2012-02-18", 5], ["2012-02-19", 4], ["2012-01-14", 4], ["2012-05-23", 2], ["2012-04-14", 3], ["2012-08-30", 2], ["2012-04-15", 2], ["2012-05-21", 2], ["2012-12-28", 4], ["2012-09-03", 1], ["2012-01-10", 5], ["2012-09-17", 1], ["2012-04-17", 1], ["2012-05-24", 3], ["2012-04-19", 1], ["2012-05-03", 2], ["2012-09-29", 5], ["2012-09-15", 3], ["2012-03-29", 1], ["2012-02-05", 1], ["2012-02-04", 9], ["2012-02-07", 2], ["2012-09-14", 6], ["2012-09-01", 1], ["2012-02-29", 7], ["2012-02-03", 4], ["2012-02-02", 2], ["2012-09-13", 2], ["2012-02-09", 5], ["2012-02-08", 6], ["2012-09-12", 2], ["2012-03-08", 2], ["2012-03-09", 2], ["2012-01-19", 5], ["2012-03-02", 5], ["2012-03-03", 3], ["2012-01-18", 9], ["2012-03-07", 3], ["2012-03-04", 2], ["2012-03-05", 5], ["2012-07-06", 2], ["2012-04-29", 1], ["2012-03-27", 4], ["2012-01-28", 5], ["2012-07-07", 4], ["2012-01-26", 6], ["2012-01-27", 2], ["2012-01-23", 5], ["2012-01-20", 2], ["2012-03-21", 2], ["2012-07-29", 8], ["2012-09-27", 2], ["2012-09-24", 3], ["2012-09-25", 4], ["2012-09-23", 3], ["2012-09-20", 2], ["2012-09-21", 5], ["2012-07-02", 7], ["2012-05-20", 4], ["2012-08-31", 2], ["2012-05-27", 2], ["2012-09-28", 3], ["2012-08-06", 3], ["2012-05-15", 4], ["2012-09-09", 4], ["2012-05-14", 2], ["2012-09-16", 1], ["2012-03-19", 5], ["2012-03-18", 5], ["2012-05-11", 5], ["2012-05-05", 2], ["2012-03-11", 1], ["2012-03-10", 1], ["2012-03-13", 3], ["2012-03-12", 2], ["2012-03-15", 3], ["2012-05-19", 2], ["2012-03-17", 3], ["2012-03-16", 3], ["2012-04-11", 4], ["2012-05-18", 2], ["2012-06-19", 2], ["2012-01-07", 1], ["2012-01-30", 5], ["2012-04-30", 2], ["2012-08-29", 3], ["2012-08-28", 4], ["2012-06-10", 4], ["2012-06-11", 3], ["2012-06-16", 1], ["2012-07-08", 2], ["2012-06-14", 1], ["2012-04-24", 4], ["2012-08-21", 2], ["2012-05-30", 3], ["2012-08-23", 2], ["2012-07-09", 4], ["2012-08-25", 3], ["2012-08-24", 3], ["2012-08-27", 2], ["2012-08-26", 1], ["2012-11-16", 2], ["2012-11-17", 3], ["2012-11-14", 2], ["2012-11-15", 1], ["2012-05-25", 6], ["2012-11-13", 5], ["2012-11-10", 2], ["2012-11-11", 5], ["2012-04-21", 5], ["2012-11-18", 3], ["2012-11-19", 1], ["2012-02-06", 3], ["2012-12-19", 1], ["2012-08-22", 1], ["2012-03-24", 4], ["2012-03-25", 5], ["2012-03-26", 6], ["2012-07-30", 4], ["2012-03-20", 5], ["2012-01-29", 7], ["2012-03-22", 3], ["2012-03-23", 2], ["2012-09-08", 1], ["2012-01-01", 6], ["2012-01-02", 5], ["2012-01-03", 5], ["2012-01-04", 6], ["2012-01-06", 4], ["2012-02-25", 5], ["2012-01-08", 2], ["2012-01-09", 3], ["2012-04-27", 2], ["2012-04-26", 2], ["2012-09-04", 3], ["2012-09-05", 3], ["2012-09-07", 2], ["2012-06-01", 3], ["2012-06-03", 4], ["2012-06-02", 3], ["2012-08-18", 1], ["2012-05-09", 2], ["2012-06-07", 5], ["2012-06-06", 4], ["2012-08-14", 5], ["2012-06-05", 6], ["2012-08-16", 1], ["2012-08-17", 3], ["2012-05-01", 2], ["2012-08-12", 3], ["2012-08-13", 3], ["2012-11-05", 1], ["2012-11-04", 3], ["2012-11-06", 3], ["2012-11-01", 3], ["2012-04-20", 5], ["2012-11-03", 1], ["2012-11-02", 2], ["2012-09-02", 5], ["2012-11-09", 2], ["2012-11-08", 3], ["2012-06-09", 3], ["2012-03-31", 4], ["2012-10-09", 1], ["2012-07-20", 8], ["2012-08-15", 1], ["2012-10-02", 1], ["2012-10-03", 1], ["2012-10-01", 3], ["2012-10-06", 1], ["2012-10-07", 1], ["2012-10-04", 2], ["2012-10-05", 1], ["2012-01-17", 7], ["2012-01-16", 3], ["2012-04-18", 5], ["2012-04-13", 2], ["2012-01-13", 4], ["2012-01-12", 4], ["2012-09-19", 4], ["2012-12-29", 3], ["2012-12-26", 4], ["2012-12-27", 6], ["2012-12-24", 3], ["2012-12-25", 2], ["2012-12-22", 4], ["2012-12-23", 3], ["2012-12-20", 1], ["2012-12-21", 3], ["2012-08-03", 4], ["2012-08-02", 5], ["2012-07-04", 2], ["2012-07-05", 4], ["2012-06-30", 2], ["2012-07-03", 4], ["2012-08-05", 4], ["2012-08-04", 4], ["2012-02-27", 6], ["2012-02-26", 3], ["2012-08-09", 4], ["2012-02-24", 4], ["2012-02-23", 2], ["2012-02-22", 4], ["2012-02-21", 8], ["2012-02-20", 7], ["2012-09-18", 5], ["2012-04-22", 3], ["2012-03-30", 6], ["2012-02-17", 4], ["2012-08-01", 4], ["2012-10-19", 24], ["2012-10-18", 2], ["2012-05-08", 6], ["2012-10-11", 4], ["2012-10-10", 3], ["2012-10-13", 1], ["2012-10-12", 3], ["2012-10-15", 2], ["2012-10-14", 1], ["2012-10-17", 3], ["2012-10-16", 2], ["2012-04-07", 5], ["2012-06-12", 4], ["2012-04-05", 3], ["2012-06-28", 1], ["2012-04-03", 1], ["2012-09-11", 1], ["2012-04-01", 1], ["2012-06-13", 5], ["2012-06-23", 4], ["2012-06-22", 2], ["2012-06-21", 4], ["2012-06-20", 4], ["2012-12-31", 2], ["2012-12-30", 3], ["2012-06-25", 4], ["2012-04-08", 6], ["2012-07-15", 4], ["2012-07-14", 4], ["2012-07-17", 3], ["2012-07-16", 3], ["2012-07-11", 3], ["2012-07-10", 5], ["2012-07-13", 2], ["2012-07-12", 3], ["2012-06-08", 1], ["2012-07-19", 2], ["2012-07-18", 2], ["2012-05-12", 6], ["2012-05-10", 1], ["2012-05-02", 3], ["2012-06-04", 6], ["2012-04-06", 8], ["2012-06-15", 5], ["2012-06-29", 6], ["2012-05-31", 2], ["2012-05-13", 9], ["2012-08-20", 1], ["2012-10-24", 1], ["2012-10-26", 1], ["2012-10-27", 4], ["2012-10-20", 2], ["2012-10-21", 4], ["2012-10-22", 2], ["2012-10-23", 2], ["2012-07-28", 4], ["2012-12-01", 1], ["2012-12-02", 3], ["2012-12-03", 2], ["2012-12-04", 4], ["2012-12-05", 2], ["2012-12-06", 6], ["2012-12-07", 2], ["2012-12-08", 3], ["2012-12-09", 1], ["2012-07-22", 3], ["2012-07-23", 2], ["2012-07-24", 2], ["2012-07-25", 3], ["2012-07-26", 2], ["2012-07-27", 3], ["2012-03-14", 2], ["2012-07-01", 2], ["2012-03-01", 3], ["2012-01-11", 6],
        //         ["2013-09-09", 2], ["2013-09-08", 2], ["2013-09-01", 2], ["2013-04-10", 3], ["2013-09-03", 2], ["2013-09-02", 4], ["2013-09-05", 3], ["2013-09-04", 3], ["2013-04-17", 2], ["2013-09-06", 2], ["2013-12-29", 2], ["2013-12-28", 2], ["2013-12-23", 2], ["2013-12-22", 3], ["2013-12-21", 4], ["2013-12-20", 2], ["2013-12-27", 1], ["2013-12-26", 3], ["2013-12-25", 2], ["2013-12-24", 6], ["2013-04-18", 1], ["2013-07-14", 5], ["2013-07-15", 1], ["2013-07-16", 4], ["2013-07-17", 1], ["2013-07-10", 1], ["2013-07-11", 1], ["2013-07-12", 1], ["2013-01-06", 3], ["2013-01-09", 2], ["2013-01-08", 3], ["2013-07-18", 3], ["2013-07-19", 3], ["2013-04-11", 1], ["2013-04-13", 2], ["2013-03-10", 1], ["2013-03-11", 2], ["2013-03-12", 1], ["2013-03-13", 2], ["2013-03-14", 3], ["2013-03-15", 2], ["2013-03-16", 2], ["2013-03-17", 1], ["2013-03-18", 3], ["2013-04-15", 1], ["2013-04-14", 1], ["2013-09-07", 1], ["2013-04-16", 1], ["2013-08-20", 1], ["2013-08-21", 2], ["2013-08-22", 2], ["2013-08-23", 1], ["2013-08-24", 1], ["2013-08-25", 1], ["2013-08-26", 3], ["2013-08-27", 2], ["2013-08-28", 1], ["2013-08-29", 5], ["2013-12-12", 1], ["2013-12-13", 4], ["2013-12-10", 2], ["2013-12-11", 4], ["2013-12-16", 1], ["2013-12-17", 3], ["2013-12-14", 2], ["2013-12-15", 2], ["2013-12-18", 2], ["2013-12-19", 2], ["2013-10-29", 2], ["2013-10-28", 1], ["2013-10-25", 1], ["2013-10-24", 2], ["2013-10-27", 2], ["2013-10-26", 1], ["2013-10-21", 1], ["2013-10-20", 1], ["2013-10-23", 1], ["2013-04-12", 4], ["2013-11-13", 1], ["2013-11-12", 2], ["2013-11-10", 2], ["2013-11-17", 3], ["2013-11-16", 2], ["2013-11-15", 1], ["2013-11-14", 2], ["2013-11-19", 1], ["2013-11-18", 1], ["2013-06-30", 4], ["2013-04-28", 2], ["2013-04-29", 5], ["2013-04-24", 1], ["2013-04-25", 4], ["2013-04-26", 3], ["2013-04-27", 2], ["2013-09-30", 1], ["2013-04-21", 1], ["2013-04-22", 1], ["2013-04-23", 4], ["2013-05-30", 5], ["2013-05-31", 1], ["2013-01-01", 4], ["2013-07-08", 4], ["2013-07-03", 4], ["2013-07-02", 1], ["2013-07-01", 5], ["2013-07-06", 2], ["2013-07-05", 5], ["2013-07-04", 1], ["2013-01-02", 1], ["2013-01-31", 3], ["2013-01-05", 2], ["2013-01-04", 2], ["2013-01-07", 4], ["2013-07-13", 2], ["2013-03-06", 1], ["2013-03-05", 1], ["2013-03-04", 4], ["2013-03-03", 2], ["2013-03-02", 2], ["2013-03-01", 2], ["2013-09-18", 3], ["2013-03-09", 1], ["2013-03-08", 4], ["2013-09-19", 1], ["2013-09-11", 2], ["2013-09-16", 1], ["2013-09-17", 3], ["2013-11-28", 2], ["2013-11-29", 2], ["2013-09-14", 2], ["2013-11-22", 1], ["2013-11-23", 2], ["2013-11-20", 3], ["2013-11-21", 2], ["2013-11-26", 3], ["2013-11-25", 2], ["2013-01-03", 3], ["2013-04-30", 5], ["2013-08-31", 1], ["2013-08-30", 2], ["2013-12-01", 1], ["2013-12-03", 1], ["2013-12-02", 1], ["2013-12-07", 2], ["2013-12-06", 1], ["2013-12-09", 1], ["2013-12-08", 2], ["2013-10-10", 2], ["2013-10-11", 1], ["2013-10-12", 1], ["2013-10-13", 2], ["2013-10-14", 1], ["2013-10-15", 1], ["2013-10-16", 2], ["2013-10-17", 1], ["2013-10-18", 1], ["2013-10-19", 1], ["2013-07-30", 1], ["2013-07-31", 2], ["2013-03-19", 3], ["2013-03-30", 4], ["2013-03-31", 3], ["2013-06-01", 1], ["2013-06-02", 4], ["2013-06-03", 2], ["2013-06-04", 2], ["2013-06-05", 4], ["2013-06-06", 2], ["2013-06-07", 1], ["2013-06-08", 3], ["2013-06-09", 2], ["2013-02-08", 3], ["2013-02-09", 2], ["2013-02-04", 1], ["2013-02-05", 1], ["2013-02-06", 2], ["2013-02-07", 3], ["2013-02-01", 1], ["2013-02-02", 1], ["2013-02-03", 2], ["2013-09-23", 4], ["2013-09-22", 3], ["2013-09-21", 4], ["2013-09-20", 3], ["2013-09-27", 3], ["2013-09-26", 2], ["2013-09-25", 1], ["2013-09-24", 3], ["2013-09-29", 1], ["2013-09-28", 2], ["2013-05-29", 3], ["2013-05-28", 1], ["2013-05-27", 4], ["2013-05-26", 3], ["2013-05-25", 1], ["2013-05-24", 3], ["2013-05-23", 6], ["2013-05-22", 4], ["2013-05-21", 5], ["2013-05-20", 3], ["2013-08-08", 1], ["2013-08-09", 2], ["2013-08-06", 2], ["2013-08-07", 2], ["2013-08-04", 2], ["2013-08-05", 2], ["2013-08-02", 2], ["2013-08-03", 4], ["2013-08-01", 2], ["2013-01-29", 1], ["2013-01-28", 3], ["2013-01-23", 2], ["2013-01-22", 2], ["2013-01-21", 4], ["2013-01-20", 3], ["2013-01-27", 1], ["2013-01-26", 1], ["2013-01-25", 4], ["2013-01-24", 2], ["2013-01-12", 4], ["2013-01-10", 4], ["2013-01-11", 1], ["2013-07-25", 2], ["2013-01-17", 4], ["2013-01-14", 1], ["2013-01-15", 1], ["2013-05-16", 3], ["2013-05-17", 1], ["2013-05-14", 1], ["2013-05-15", 1], ["2013-05-12", 2], ["2013-05-13", 2], ["2013-05-10", 3], ["2013-05-11", 4], ["2013-05-18", 4], ["2013-04-08", 7], ["2013-04-09", 3], ["2013-04-02", 2], ["2013-04-03", 1], ["2013-09-10", 1], ["2013-04-01", 2], ["2013-04-06", 3], ["2013-04-07", 2], ["2013-04-04", 1], ["2013-04-05", 2], ["2013-12-30", 2], ["2013-12-31", 3], ["2013-10-07", 2], ["2013-10-06", 2], ["2013-10-05", 1], ["2013-10-04", 1], ["2013-10-03", 2], ["2013-10-02", 2], ["2013-10-01", 1], ["2013-04-20", 1], ["2013-10-09", 2], ["2013-10-08", 1], ["2013-07-21", 4], ["2013-01-13", 3], ["2013-07-23", 3], ["2013-07-22", 2], ["2013-01-16", 3], ["2013-07-24", 1], ["2013-07-27", 1], ["2013-07-26", 2], ["2013-07-29", 1], ["2013-07-28", 4], ["2013-01-18", 1], ["2013-01-19", 2], ["2013-03-29", 4], ["2013-03-28", 1], ["2013-03-25", 3], ["2013-03-24", 3], ["2013-03-27", 1], ["2013-03-26", 2], ["2013-03-21", 1], ["2013-03-20", 2], ["2013-03-23", 1], ["2013-03-22", 4], ["2013-06-17", 4], ["2013-06-16", 2], ["2013-06-15", 3], ["2013-06-14", 3], ["2013-06-13", 3], ["2013-06-12", 3], ["2013-06-11", 4], ["2013-06-10", 5], ["2013-06-19", 1], ["2013-06-18", 2], ["2013-02-13", 5], ["2013-02-12", 4], ["2013-02-11", 1], ["2013-02-10", 1], ["2013-02-17", 4], ["2013-02-16", 3], ["2013-02-15", 3], ["2013-02-14", 1], ["2013-02-19", 2], ["2013-02-18", 3], ["2013-09-15", 3], ["2013-08-19", 2], ["2013-08-18", 1], ["2013-08-15", 2], ["2013-08-14", 1], ["2013-08-17", 1], ["2013-08-16", 2], ["2013-08-11", 2], ["2013-08-10", 2], ["2013-08-13", 1], ["2013-10-30", 1], ["2013-10-31", 2], ["2013-11-09", 1], ["2013-11-07", 1], ["2013-11-01", 1], ["2013-11-02", 2], ["2013-11-03", 1], ["2013-05-05", 3], ["2013-05-04", 3], ["2013-05-07", 5], ["2013-05-06", 1], ["2013-05-01", 3], ["2013-05-09", 3], ["2013-05-08", 3], ["2013-06-28", 3], ["2013-06-29", 2], ["2013-06-26", 1], ["2013-06-27", 2], ["2013-06-24", 5], ["2013-06-25", 2], ["2013-06-22", 3], ["2013-06-23", 5], ["2013-06-20", 3], ["2013-06-21", 3], ["2013-02-28", 3], ["2013-02-22", 2], ["2013-02-23", 2], ["2013-02-20", 4], ["2013-02-21", 1], ["2013-02-26", 4], ["2013-02-27", 3], ["2013-02-24", 3], ["2013-02-25", 2],
        //         ["2014-01-15", 1], ["2014-06-30", 1], ["2014-08-28", 1], ["2014-06-09", 1], ["2014-03-12", 1], ["2014-03-14", 1], ["2014-03-11", 2], ["2014-04-16", 1], ["2014-04-17", 1], ["2014-04-14", 1], ["2014-04-15", 2], ["2014-04-12", 1], ["2014-04-10", 1], ["2014-04-11", 1], ["2014-01-11", 2], ["2014-07-29", 1], ["2014-07-16", 2], ["2014-04-18", 2], ["2014-04-19", 2], ["2014-01-28", 1], ["2014-03-01", 1], ["2014-09-19", 1], ["2014-09-18", 1], ["2014-10-01", 1], ["2014-09-15", 2], ["2014-09-14", 2], ["2014-09-17", 1], ["2014-09-16", 2], ["2014-09-11", 1], ["2014-10-02", 1], ["2014-09-13", 1], ["2014-09-12", 1], ["2014-10-03", 1], ["2014-01-14", 3], ["2014-08-05", 1], ["2014-10-26", 1], ["2014-02-03", 2], ["2014-02-25", 2], ["2014-06-21", 2], ["2014-06-20", 1], ["2014-03-28", 1], ["2014-03-29", 1], ["2014-06-25", 1], ["2014-06-24", 4], ["2014-06-27", 2], ["2014-06-26", 2], ["2014-03-22", 2], ["2014-06-28", 2], ["2014-03-20", 1], ["2014-03-21", 1], ["2014-03-26", 1], ["2014-03-27", 1], ["2014-03-25", 1], ["2014-04-05", 1], ["2014-10-08", 1], ["2014-04-07", 1], ["2014-04-06", 1], ["2014-04-01", 1], ["2014-04-03", 2], ["2014-04-02", 1], ["2014-07-14", 2], ["2014-04-21", 2], ["2014-04-09", 1], ["2014-04-08", 1], ["2014-09-20", 1], ["2014-05-08", 2], ["2014-09-23", 1], ["2014-09-24", 1], ["2014-09-26", 1], ["2014-09-27", 2], ["2014-05-02", 1], ["2014-09-29", 1], ["2014-05-06", 1], ["2014-05-07", 2], ["2014-05-04", 1], ["2014-05-05", 1], ["2014-09-28", 1], ["2014-05-09", 1], ["2014-02-09", 1], ["2014-12-10", 1], ["2014-07-26", 1], ["2014-07-27", 1], ["2014-07-24", 2], ["2014-07-25", 1], ["2014-07-22", 1], ["2014-07-23", 1], ["2014-07-20", 2], ["2014-07-21", 2], ["2014-06-14", 1], ["2014-06-15", 1], ["2014-06-16", 1], ["2014-06-17", 1], ["2014-05-27", 2], ["2014-06-11", 2], ["2014-03-23", 2], ["2014-06-13", 1], ["2014-04-30", 1], ["2014-03-30", 1], ["2014-03-10", 1], ["2014-06-01", 2], ["2014-06-18", 1], ["2014-06-19", 2], ["2014-08-31", 1], ["2014-02-06", 1], ["2014-01-31", 2], ["2014-03-09", 1], ["2014-05-19", 3], ["2014-09-30", 1], ["2014-05-10", 2], ["2014-05-13", 2], ["2014-05-12", 3], ["2014-05-15", 1], ["2014-05-14", 1], ["2014-05-17", 3], ["2014-05-16", 1], ["2014-02-21", 1], ["2014-12-15", 1], ["2014-07-31", 1], ["2014-07-30", 1], ["2014-01-06", 2], ["2014-01-07", 2], ["2014-11-30", 2], ["2014-01-05", 2], ["2014-03-08", 1], ["2014-08-24", 1], ["2014-04-29", 2], ["2014-04-28", 1], ["2014-03-04", 1], ["2014-04-26", 1], ["2014-04-25", 1], ["2014-04-24", 1], ["2014-04-23", 1], ["2014-05-31", 1], ["2014-03-02", 1], ["2014-03-03", 2], ["2014-10-20", 1], ["2014-01-08", 1], ["2014-01-09", 4], ["2014-03-15", 1], ["2014-08-19", 1], ["2014-05-28", 2], ["2014-06-06", 1], ["2014-05-24", 3], ["2014-05-25", 2], ["2014-08-10", 1], ["2014-08-11", 1], ["2014-08-16", 1], ["2014-05-21", 1], ["2014-08-14", 1], ["2014-08-15", 1], ["2014-08-01", 1], ["2014-07-02", 2], ["2014-07-03", 1], ["2014-07-04", 1], ["2014-07-05", 1], ["2014-07-07", 1], ["2014-07-08", 1], ["2014-11-21", 1], ["2014-11-20", 1], ["2014-01-17", 1], ["2014-08-02", 1], ["2014-11-25", 1], ["2014-11-24", 1], ["2014-11-27", 1], ["2014-01-12", 2], ["2014-01-16", 1], ["2014-11-28", 1], ["2014-03-18", 1], ["2014-01-19", 2], ["2014-06-05", 1], ["2014-08-04", 1], ["2014-02-22", 1], ["2014-08-07", 1], ["2014-08-06", 1], ["2014-08-29", 1], ["2014-08-09", 1], ["2014-08-08", 2], ["2014-12-08", 1], ["2014-02-01", 2], ["2014-12-02", 2], ["2014-12-03", 1], ["2014-08-03", 3], ["2014-12-01", 2], ["2014-12-06", 1], ["2014-12-07", 1], ["2014-12-04", 2], ["2014-12-05", 2], ["2014-07-17", 2], ["2014-03-31", 1], ["2014-07-15", 1], ["2014-06-08", 2], ["2014-07-13", 1], ["2014-07-12", 1], ["2014-10-28", 1], ["2014-07-10", 1], ["2014-06-03", 2], ["2014-10-27", 2], ["2014-10-24", 1], ["2014-02-26", 1], ["2014-10-22", 2], ["2014-10-23", 2], ["2014-02-23", 1], ["2014-07-18", 1], ["2014-11-14", 1], ["2014-11-15", 2], ["2014-11-16", 1], ["2014-11-17", 1], ["2014-01-10", 3], ["2014-07-11", 1], ["2014-11-12", 1], ["2014-11-13", 1], ["2014-11-19", 1], ["2014-10-18", 1], ["2014-04-22", 2], ["2014-09-22", 1], ["2014-06-02", 1], ["2014-01-04", 3], ["2014-02-27", 1], ["2014-05-29", 2], ["2014-12-18", 1], ["2014-01-13", 2], ["2014-10-25", 1], ["2014-12-11", 1], ["2014-06-07", 1], ["2014-12-13", 1], ["2014-08-30", 1], ["2014-12-14", 1], ["2014-12-17", 1], ["2014-12-16", 1], ["2014-03-05", 2], ["2014-02-11", 1], ["2014-02-12", 1], ["2014-02-13", 1], ["2014-02-15", 1], ["2014-02-16", 1], ["2014-08-13", 1], ["2014-02-18", 1], ["2014-02-19", 1], ["2014-06-04", 1], ["2014-10-31", 1], ["2014-10-30", 1], ["2014-03-16", 1], ["2014-03-13", 1], ["2014-05-20", 2], ["2014-06-23", 4], ["2014-04-20", 1], ["2014-03-07", 2], ["2014-01-02", 1], ["2014-05-22", 1], ["2014-02-20", 1], ["2014-11-10", 2], ["2014-05-23", 1], ["2014-08-23", 1], ["2014-08-22", 2], ["2014-08-21", 1], ["2014-07-19", 1], ["2014-12-28", 3], ["2014-12-29", 1], ["2014-08-25", 2], ["2014-07-01", 1], ["2014-12-24", 1], ["2014-12-25", 2], ["2014-12-26", 2], ["2014-12-27", 2], ["2014-12-21", 1], ["2014-12-22", 1], ["2014-12-23", 1], ["2014-02-07", 1], ["2014-01-29", 2], ["2014-02-05", 1], ["2014-10-14", 1], ["2014-10-04", 1], ["2014-10-06", 1], ["2014-10-07", 1], ["2014-01-20", 1], ["2014-01-21", 1], ["2014-01-22", 1], ["2014-01-23", 1], ["2014-01-24", 1], ["2014-01-25", 2], ["2014-01-26", 2], ["2014-01-27", 3], ["2014-03-06", 1], ["2014-08-27", 2], ["2014-08-26", 1], ["2014-12-31", 1], ["2014-05-26", 2], ["2014-02-28", 1], ["2014-09-08", 1], ["2014-09-06", 1], ["2014-09-07", 1], ["2014-09-04", 3], ["2014-09-05", 1], ["2014-09-03", 1], ["2014-01-01", 4], ["2014-01-03", 4], ["2014-10-17", 1], ["2014-10-16", 1], ["2014-10-15", 2], ["2014-11-08", 2], ["2014-10-13", 1], ["2014-10-19", 2], ["2014-11-03", 1], ["2014-11-01", 1], ["2014-01-30", 1], ["2014-11-07", 1], ["2014-11-06", 1], ["2014-11-05", 1], ["2014-11-04", 2],
        //         ["2015-05-03", 1], ["2015-05-02", 1], ["2015-05-01", 1], ["2015-05-06", 1], ["2015-05-05", 1], ["2015-02-02", 1], ["2015-05-09", 2], ["2015-05-08", 1], ["2015-02-03", 1], ["2015-01-18", 1], ["2015-11-18", 1], ["2015-01-19", 2], ["2015-07-18", 1], ["2015-01-06", 1], ["2015-11-11", 1], ["2015-07-17", 2], ["2015-11-13", 1], ["2015-01-13", 1], ["2015-11-15", 1], ["2015-11-14", 1], ["2015-11-17", 1], ["2015-07-11", 1], ["2015-01-04", 1], ["2015-11-20", 1], ["2015-03-30", 1], ["2015-03-31", 1], ["2015-12-21", 1], ["2015-12-22", 1], ["2015-09-15", 1], ["2015-12-27", 1], ["2015-12-26", 2], ["2015-09-18", 2], ["2015-12-28", 1], ["2015-04-02", 1], ["2015-04-03", 1], ["2015-04-05", 1], ["2015-04-06", 1], ["2015-04-07", 1], ["2015-11-29", 1], ["2015-01-08", 1], ["2015-11-24", 1], ["2015-07-04", 2], ["2015-07-07", 1], ["2015-11-27", 1], ["2015-07-01", 2], ["2015-01-02", 2], ["2015-07-03", 2], ["2015-03-23", 1], ["2015-03-21", 1], ["2015-03-20", 1], ["2015-03-27", 1], ["2015-03-25", 1], ["2015-03-24", 1], ["2015-03-29", 1], ["2015-03-28", 1], ["2015-06-02", 1], ["2015-06-03", 1], ["2015-09-05", 4], ["2015-09-04", 2], ["2015-06-06", 1], ["2015-12-11", 1], ["2015-12-12", 1], ["2015-04-18", 1], ["2015-04-17", 2], ["2015-04-16", 1], ["2015-04-15", 1], ["2015-04-11", 1], ["2015-09-09", 1], ["2015-04-10", 1], ["2015-01-10", 2], ["2015-01-12", 1], ["2015-12-09", 1], ["2015-02-08", 1], ["2015-02-09", 1], ["2015-12-03", 2], ["2015-02-07", 1], ["2015-12-01", 1], ["2015-02-05", 1], ["2015-12-07", 1], ["2015-12-16", 1], ["2015-02-01", 1], ["2015-06-10", 1], ["2015-06-13", 1], ["2015-01-05", 1], ["2015-06-14", 1], ["2015-06-17", 1], ["2015-10-28", 1], ["2015-10-27", 1], ["2015-10-26", 1], ["2015-10-24", 1], ["2015-10-21", 1], ["2015-09-01", 4], ["2015-06-05", 1], ["2015-05-11", 1], ["2015-07-27", 1], ["2015-07-26", 1], ["2015-07-25", 1], ["2015-07-23", 1], ["2015-07-22", 1], ["2015-07-20", 2], ["2015-06-08", 1], ["2015-07-29", 1], ["2015-02-19", 1], ["2015-02-18", 2], ["2015-02-15", 1], ["2015-02-14", 1], ["2015-02-17", 1], ["2015-02-13", 2], ["2015-06-24", 1], ["2015-06-26", 1], ["2015-06-27", 1], ["2015-06-21", 7], ["2015-06-22", 1], ["2015-09-08", 1], ["2015-06-28", 1], ["2015-05-20", 2], ["2015-05-29", 1], ["2015-08-29", 1], ["2015-05-28", 1], ["2015-08-22", 2], ["2015-08-23", 1], ["2015-08-20", 1], ["2015-08-21", 2], ["2015-01-24", 3], ["2015-02-21", 1], ["2015-02-23", 1], ["2015-02-24", 2], ["2015-02-25", 1], ["2015-02-26", 1], ["2015-02-27", 2], ["2015-02-28", 1], ["2015-07-05", 1], ["2015-06-30", 1], ["2015-09-13", 1], ["2015-04-01", 2], ["2015-05-23", 1], ["2015-04-26", 2], ["2015-04-27", 1], ["2015-04-24", 1], ["2015-05-22", 1], ["2015-04-22", 1], ["2015-09-16", 1], ["2015-04-20", 1], ["2015-04-21", 2], ["2015-08-31", 4], ["2015-04-28", 1], ["2015-04-29", 2], ["2015-05-27", 1], ["2015-09-19", 1], ["2015-05-26", 2], ["2015-05-24", 1], ["2015-10-16", 1], ["2015-10-17", 1], ["2015-08-08", 1], ["2015-04-30", 1], ["2015-05-21", 1], ["2015-01-29", 2], ["2015-08-06", 1], ["2015-08-07", 2], ["2015-05-25", 2], ["2015-08-01", 2], ["2015-10-18", 1], ["2015-10-19", 2], ["2015-04-25", 2], ["2015-01-16", 1], ["2015-04-23", 1], ["2015-12-10", 1], ["2015-01-30", 2], ["2015-01-31", 1], ["2015-03-13", 2], ["2015-03-10", 2], ["2015-03-11", 1], ["2015-03-16", 1], ["2015-03-17", 1], ["2015-03-14", 2], ["2015-03-15", 1], ["2015-09-30", 1], ["2015-10-05", 2], ["2015-10-07", 2], ["2015-10-01", 1], ["2015-05-14", 1], ["2015-05-15", 1], ["2015-08-19", 1], ["2015-05-17", 1], ["2015-10-08", 1], ["2015-05-13", 1], ["2015-11-08", 1], ["2015-11-09", 1], ["2015-11-06", 2], ["2015-11-07", 1], ["2015-11-05", 1], ["2015-01-25", 1], ["2015-03-08", 1], ["2015-01-27", 1], ["2015-01-26", 2], ["2015-01-21", 2], ["2015-01-20", 1], ["2015-01-23", 1], ["2015-09-10", 4], ["2015-03-01", 1], ["2015-03-02", 1], ["2015-03-05", 1], ["2015-03-04", 2], ["2015-03-07", 1], ["2015-03-06", 1], ["2015-09-03", 3], ["2015-12-30", 1], ["2015-09-29", 1], ["2015-09-24", 2], ["2015-09-21", 2], ["2015-09-20", 2], ["2015-09-23", 1], ["2015-07-08", 2],
        //         ["2016-01-04", 1], ["2016-06-25", 2], ["2016-06-24", 1], ["2016-06-22", 2], ["2016-01-02", 2], ["2016-06-20", 1], ["2016-06-28", 1], ["2016-03-06", 1], ["2016-03-07", 1], ["2016-03-05", 2], ["2016-03-02", 1], ["2016-03-03", 1], ["2016-01-19", 1], ["2016-09-29", 2], ["2016-01-13", 1], ["2016-01-17", 2], ["2016-12-21", 1], ["2016-12-24", 1], ["2016-12-28", 1], ["2016-02-23", 1], ["2016-02-27", 2], ["2016-02-26", 2], ["2016-02-25", 1], ["2016-11-12", 2], ["2016-11-13", 1], ["2016-11-11", 1], ["2016-11-16", 1], ["2016-11-14", 1], ["2016-11-15", 2], ["2016-08-31", 1], ["2016-09-30", 1], ["2016-12-30", 1], ["2016-11-09", 1], ["2016-03-23", 1], ["2016-03-27", 1], ["2016-11-03", 1], ["2016-08-21", 1], ["2016-08-20", 1], ["2016-08-22", 1], ["2016-05-21", 1], ["2016-09-05", 1], ["2016-09-07", 1], ["2016-01-01", 1], ["2016-12-06", 1], ["2016-12-07", 1], ["2016-12-02", 1], ["2016-03-13", 1], ["2016-11-30", 1], ["2016-08-10", 1], ["2016-08-18", 1], ["2016-08-19", 2], ["2016-04-29", 1], ["2016-04-21", 1], ["2016-04-23", 2], ["2016-04-25", 1], ["2016-04-24", 1], ["2016-04-27", 1], ["2016-04-26", 1], ["2016-05-18", 1], ["2016-11-23", 2], ["2016-11-22", 1], ["2016-11-20", 1], ["2016-11-27", 1], ["2016-10-13", 1], ["2016-07-02", 1], ["2016-07-03", 1], ["2016-07-06", 1], ["2016-05-02", 1], ["2016-05-03", 1], ["2016-05-06", 1], ["2016-05-07", 1], ["2016-04-14", 2], ["2016-04-16", 1], ["2016-04-17", 1], ["2016-04-10", 2], ["2016-04-11", 1], ["2016-04-12", 1], ["2016-06-13", 2], ["2016-06-11", 1], ["2016-10-24", 1], ["2016-10-26", 2], ["2016-10-28", 1], ["2016-05-08", 1], ["2016-07-16", 1], ["2016-05-17", 1], ["2016-05-13", 1], ["2016-04-03", 1], ["2016-04-02", 1], ["2016-04-07", 2], ["2016-04-09", 2], ["2016-01-23", 1], ["2016-01-20", 1], ["2016-01-27", 2], ["2016-01-24", 1], ["2016-01-25", 1], ["2016-01-28", 1], ["2016-01-29", 2], ["2016-01-06", 1], ["2016-02-18", 1], ["2016-02-19", 1], ["2016-10-31", 1], ["2016-02-10", 1], ["2016-02-14", 1], ["2016-08-09", 1], ["2016-01-31", 1], ["2016-02-04", 2], ["2016-02-09", 1], ["2016-02-08", 1], ["2016-01-18", 1], ["2016-02-01", 1], ["2016-02-03", 2], ["2016-02-02", 1], ["2016-06-07", 1], ["2016-02-07", 2], ["2016-02-06", 1],
        //         ["2017-05-25", 1], ["2017-06-08", 1], ["2017-06-09", 1], ["2017-06-01", 1], ["2017-06-03", 1], ["2017-02-28", 1], ["2017-02-26", 2], ["2017-02-27", 1], ["2017-02-24", 1], ["2017-02-25", 1], ["2017-02-22", 1], ["2017-02-23", 1], ["2017-02-20", 3], ["2017-02-21", 1], ["2017-06-13", 1], ["2017-05-10", 1], ["2017-06-10", 1], ["2017-05-16", 1], ["2017-05-17", 1], ["2017-06-15", 2], ["2017-07-06", 1], ["2017-07-19", 1], ["2017-06-14", 2], ["2017-03-09", 1], ["2017-01-17", 1], ["2017-02-14", 2], ["2017-01-10", 1], ["2017-01-11", 1], ["2017-05-18", 1], ["2017-01-18", 1], ["2017-01-19", 1], ["2017-07-24", 1], ["2017-07-20", 1], ["2017-07-23", 1], ["2017-03-21", 1], ["2017-03-20", 1], ["2017-05-03", 1], ["2017-05-02", 1], ["2017-05-05", 1], ["2017-03-24", 1], ["2017-04-01", 1], ["2017-03-29", 1], ["2017-03-28", 1], ["2017-04-08", 1], ["2017-01-05", 1], ["2017-01-04", 1], ["2017-01-06", 1], ["2017-01-01", 1], ["2017-07-09", 1], ["2017-01-03", 1], ["2017-02-01", 1], ["2017-02-02", 1], ["2017-02-03", 1], ["2017-02-04", 1], ["2017-02-05", 2], ["2017-02-06", 1], ["2017-07-17", 2], ["2017-02-08", 1], ["2017-02-09", 1], ["2017-03-14", 1], ["2017-03-15", 1], ["2017-03-17", 1], ["2017-03-10", 2], ["2017-03-11", 1], ["2017-04-13", 1], ["2017-04-12", 1], ["2017-03-18", 1], ["2017-03-19", 1], ["2017-07-13", 1], ["2017-07-15", 1], ["2017-07-16", 1], ["2017-02-17", 1], ["2017-02-16", 1], ["2017-02-15", 3], ["2017-05-28", 2], ["2017-02-13", 1], ["2017-02-12", 1], ["2017-02-10", 2], ["2017-05-23", 1], ["2017-03-02", 1], ["2017-03-01", 1], ["2017-03-07", 1], ["2017-05-26", 1], ["2017-02-19", 1], ["2017-02-18", 1], ["2017-01-22", 2], ["2017-01-20", 1], ["2017-05-31", 1], ["2017-03-12", 2], ["2017-03-13", 1], ["2017-07-12", 1], ["2017-06-28", 1], ["2017-06-23", 1], ["2017-06-21", 1], ["2017-06-24", 1], ["2017-04-07", 1], ["2017-03-22", 1], ["2017-03-25", 1], ["2017-05-04", 1], ["2017-06-30", 1],
        //     ];
        //     return data;
        // }
        // console.log(getVirtulData);

        //----------------
        let optionData = [];
        if (this.state.monthList.length != 0) {
            this.getData(this.state.chartData);
            let chart = echarts.init(document.getElementById(this.state.divId));
            let option = {
                title: {
                    top: 5,
                    left: 'center',
                    text
                    // 老树微博，三千诗与画
                    // https://zhuanlan.zhihu.com/p/28989690
                },
                tooltip: {
                    position: 'top',
                    formatter: "{b}{c}%"

                },
                visualMap: {
                    min: 0,
                    max: 100,
                    calculable: true,
                    orient: 'vertical',
                    left: '2%',
                    top: 'center'
                },

                calendar:
                    calendarList

                // {
                //     top:60,
                //     range: ['2011-01-01', '2011-12-31'], 
                //     cellSize: ['auto', 15],
                //     left: 70,
                //     right: 30,
                // },
                // {
                //     top: 230,
                //     range: '2012',
                //     cellSize: ['auto', 15],
                //     left: 70,
                //     right: 30,
                // },
                // {
                //     top: 400,
                //     range: '2013',
                //     cellSize: ['auto', 15],
                //     left: 70,
                //     right: 30,
                // }
                ,

                series:
                    seriesList
                // [{
                //     type: 'heatmap',
                //     coordinateSystem: 'calendar',
                //     calendarIndex: 1,
                //     data: dataList
                // }, 
                // {
                //     type: 'heatmap',
                //     coordinateSystem: 'calendar',
                //     calendarIndex: 0,
                //     data: dataList
                // }, 
                // {
                //     type: 'heatmap',
                //     coordinateSystem: 'calendar',
                //     calendarIndex: 1,
                //     data: getVirtulData(2012)
                // }, {
                //     type: 'heatmap',
                //     coordinateSystem: 'calendar',
                //     calendarIndex: 2,
                //     data: getVirtulData(2013)
                // }


            };
            // let option = {
            //     baseOption: {
            //         tooltip: {},
            //         legend: {
            //             data: ["未巡", "已巡"],
            //             top: 0
            //         },
            //         toolbox: {
            //             show: true,
            //             feature: {
            //                 // dataZoom: {},
            //                 // dataView: { readOnly: false },
            //                 // restore: {},
            //                 saveAsImage: {},
            //                 myFullScreen: {
            //                     show: this.state.fullScreenShow,
            //                     title: '全屏查看',
            //                     icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
            //                     onclick: (e) => {
            //                         var opts = e.getOption()
            //                         opts.toolbox[0].feature.myFullScreen.show = false;
            //                         this.state.that.setFullScreen('巡更完成情况总览', opts);
            //                     }
            //                 }
            //             }
            //         },
            //         calendar: [{
            //             top: 'middle',
            //             left: 'center',
            //             orient: 'vertical',
            //             cellSize: this.state.cellSize,
            //             yearLabel: {
            //                 show: false,
            //                 textStyle: {
            //                     fontSize: 30
            //                 }
            //             },
            //             dayLabel: {
            //                 margin: 20,
            //                 firstDay: 1,
            //                 nameMap: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
            //             },
            //             monthLabel: {
            //                 show: false
            //             },
            //         }],
            //         series: [{
            //             type: 'effectScatter',
            //             coordinateSystem: 'calendar',
            //             label: {
            //                 normal: {
            //                     show: true,
            //                     formatter: (params) => {
            //                         return echarts.format.formatTime('dd', params.value[0]);
            //                     },
            //                     offset: [-this.state.cellSize[0] / 2 + 10, -this.state.cellSize[1] / 2 + 10],
            //                     textStyle: {
            //                         color: '#000',
            //                         fontSize: 14
            //                     }
            //                 }
            //             },
            //         }],
            //         timeline: {
            //             x: 0,
            //             axisType: 'category',
            //             orient: 'horizontal',
            //             autoPlay: true,
            //             playInterval: 5000,
            //             left: 0,
            //             right: null,
            //             bottom: 0,
            //             inverse: false,
            //             lineStyle: {
            //                 color: '#555'
            //             },
            //             label: {
            //                 formatter: function (s) {
            //                     return s;
            //                 },
            //                 normal: {
            //                     textStyle: {
            //                         color: '#000',
            //                     },
            //                 },
            //                 emphasis: {
            //                     textStyle: {
            //                         color: '#000',
            //                     },
            //                 }
            //             },
            //             controlStyle: {
            //                 normal: {
            //                     color: '#000',
            //                     borderColor: '#000'
            //                 },
            //                 emphasis: {
            //                     color: '#000',
            //                     borderColor: '#000'
            //                 } //高亮时显示颜色
            //             },
            //             data: this.state.monthList
            //         },
            //         options: optionData
            //     },
            // }
            // for (var i = 0; i < this.state.monthList.length; i++) {
            //     optionData.push({
            //         calendar: [{
            //             range: this.state.monthList[i]
            //         }],
            //         series: {
            //             symbolSize: 0.1,
            //             data: this.state.dayList[i]
            //         },
            //     });
            // }
            option.options = optionData;
            chart.setOption(option);
            // chart.setOption({
            //     series: this.getcountsPieSeries(this.state.dayList[0], chart, 0)
            // });
            // chart.on('timelinechanged', (timeLineIndex) => {
            //     chart.setOption({
            //         series: this.getPieSeries2()
            //     });
            //     chart.setOption({
            //         series: this.getcountsPieSeries(this.state.dayList[timeLineIndex.currentIndex], chart, timeLineIndex.currentIndex)
            //     });
            // });
        }
    }

    getData = (data) => {
        data.forEach((val, index) => {
            this.state.real.push(val.real);
            this.state.should.push(val.should);
            let temp = [];
            val.date.forEach(v => {
                temp.push([v, Math.floor(Math.random() * 10000)])
            })
            this.state.dayList.push(temp);
        })
    }

    getcountsPieSeries = (scatterData, chart, i) => {
        return echarts.util.map(scatterData, (item, index) => {
            var center = chart.convertToPixel('calendar', item);
            return {
                id: index + 'pie',
                type: 'pie',
                stillShowZeroSum: false,
                center: center,
                label: {
                    normal: {
                        show: true,
                        formatter: function (params) {
                            if (params.value == 0) {
                                return '';
                            } else {
                                return params.value;
                            }
                        },
                        position: 'inside'
                    }
                },
                radius: this.state.pieRadius,
                data: [{
                    name: '未巡',
                    value: this.state.should[i][index] - this.state.real[i][index]
                }, {
                    name: '已巡',
                    value: this.state.real[i][index]
                }]
            };
        });
    }

    getPieSeries2 = () => {
        var a = [];
        for (var i = 0; i < 31; i++) {
            a.push({
                id: i + 'pie',
                type: 'pie',
                label: {
                    normal: {
                        show: false,
                        formatter: '{c}',
                        position: 'inside'
                    }
                },
                radius: 0,
            });
        }
        return a;
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle}></div>)
    }
}


class electricalsafety extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // tableLoading: true,
            deviceData: [],

            isSearch: false,
            searchChartLoading: true,
            chartSearchData: {},
            chartType: '',

            fullScreenVisible: false,

            device: props.location.state === undefined ? undefined : props.location.state.record.name,
            type: props.location.state === undefined ? undefined : props.location.state.type,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        console.log("++++++++");
        this.setState({
            confirmLoading: true,
        })
        getDeviceInfoListApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    confirmLoading: false,
                    deviceData: res.data,
                });
                if (this.state.device === undefined ? false : true) {
                    console.log("!!!!!!!!!!!!!");
                    this.searchSubmit();
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            this.setState({
                searchChartLoading: true,
                isSearch: true
            });

            if (values.timePeriod != undefined) {
                values.startTime = values.timePeriod[0].format('YYYY-MM-DD HH:mm:ss');
                values.endTime = values.timePeriod[1].format('YYYY-MM-DD HH:mm:ss');
            }

            if (values.type == 'tem') {
                this.setState({
                    chartType: 'tem'
                });
                getHistoryTemperatureApi(values)
                    .then((res) => {
                        if (res.data.msg == 'no Data !!!') {
                            notification['warning']({
                                message: '当前条件查询没有数据！',
                                description: '若未填写时间段，则默认查询最近24小时的数据。请检查查询条件，亦或者设备出现问题！',
                                onClick: () => { },
                            });
                            this.setState({
                                searchChartLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                searchChartLoading: false,
                                chartSearchData: res.data,
                            });
                        }

                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            } else if (values.type == 'ele') {
                this.setState({
                    chartType: 'ele'
                })
                getHistoryElectricApi(values)
                    .then((res) => {
                        if (res.data.msg == 'no Data !!!') {
                            notification['warning']({
                                message: '当前条件查询没有数据！',
                                description: '请检查查询条件；亦或者设备出现',
                                onClick: () => { },
                            });
                            this.setState({
                                searchChartLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                searchChartLoading: false,
                                chartSearchData: res.data,
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
            chartSearchData: {},
            chartType: '',
            device: undefined,
            type: undefined,
            fullScreenVisible: false,
        })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }


    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;


        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {

        }

        let deviceOptions;
        if (this.state.deviceData.length != 0) {
            deviceOptions = this.state.deviceData.map((d, index) =>
                <Option value={d.ieme} key={d.id}>{d.name}</Option>
            );
        }

        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Skeleton loading={this.state.confirmLoading} active>
                    <Form
                        style={{
                            padding: '12px',
                            backgroundColor: '#fafafa',
                            borderRadius: 8,
                            marginBottom: 16,
                        }}
                        layout="inline"
                        onSubmit={this.searchSubmit}>
                        <Row>
                            <Col span={8}>
                                <FormItem
                                    label="设备名称"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("imei", {
                                        initialValue: this.state.device,
                                        rules: [{
                                            required: true,
                                            message: "请输入设备名称!"
                                        }]
                                    })(
                                        <AutoComplete
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            dataSource={deviceOptions}
                                            placeholder="请输入设备名称"
                                            filterOption={(inputValue, option) => {
                                                console.log(option);
                                                return (option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1)
                                            }}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={16}>
                                <FormItem
                                    label="时间段"
                                    style={{ width: '100%' }}
                                    labelCol={{
                                        sm: { span: 4 },
                                        xl: { span: 3 },
                                        xxl: { span: 2 },
                                    }}
                                    wrapperCol={{
                                        sm: { span: 20 },
                                        xl: { span: 21 },
                                        xxl: { span: 22 },
                                    }}>
                                    {getFieldDecorator("timePeriod", {
                                        rules: [{
                                            type: 'array',
                                            required: false,
                                        }]
                                    })(
                                        <RangePicker
                                            style={{ width: '100%' }}
                                            showTime={{ format: 'HH:mm:ss' }}
                                            placeholder={['开始时间', '结束时间']}
                                            format="YYYY-MM-DD HH:mm:ss" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                                <FormItem
                                    label="类别"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("type", {
                                        initialValue: this.state.type,
                                        rules: [{
                                            required: true,
                                        }]
                                    })(
                                        <Select
                                            style={{ width: '100%' }}
                                            placeholder="请选择搜索类别">
                                            <Option value={'tem'}>温度</Option>
                                            <Option value={'ele'}>电流</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                            </FormItem>
                        </Row>
                    </Form>
                </Skeleton>
                <div>
                    <div style={{
                        marginBottom: 16,
                        padding: 16,
                        width: '100%',
                        height: 500,
                        border: '1px solid',
                        borderColor: '#f5f5f5'
                    }}>
                        {this.state.isSearch ?
                            (
                                <Skeleton loading={this.state.searchChartLoading} active>
                                    <ChartEleAndTemSearch
                                        that={this}
                                        chartData={this.state.chartSearchData}
                                        type={this.state.chartType} />
                                </Skeleton>
                            ) : (
                                <Empty
                                    image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                                    imageStyle={{
                                        marginTop: 170,
                                        marginBottom: 20,
                                    }}
                                    description={
                                        <span style={{ color: '#7a7a7a' }}>
                                            未接受到数据，请按照条件搜索以展示可视化图表
                                        </span>
                                    }
                                />
                            )
                        }
                    </div>
                </div>
                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={this.state.chartType == 'tem' ? ('设备温度变化统计图') : ('设备电流变化统计图')}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />
                </Modal>
            </div>
        )
    }
}
const Electricalsafety = Form.create()(electricalsafety);

class ChartEleAndTemSearch extends Component {
    constructor(props) {
        super(props);

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;

        this.state = {
            chartData: props.chartData,
            that: props.that,
            winWidth: winWidth,
            type: props.type,
            titleText: '',
            yAxisName: '',
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.chartData) != JSON.stringify(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that,
                type: props.type
            }, () => {
                if (this.state.type == 'tem') {
                    this.setState({
                        titleText: '温度',
                        yAxisName: '温度(℃)'
                    }, () => {
                        this.drawChart();
                    })
                } else if (this.state.type == 'ele') {
                    this.setState({
                        titleText: '电流',
                        yAxisName: '电流(A)'
                    }, () => {
                        this.drawChart();
                    })
                }
            })
        }
    }

    componentDidMount() {
        if (this.state.type == 'tem') {
            this.setState({
                titleText: '温度',
                yAxisName: '温度(℃)'
            }, () => {
                this.drawChart();
            })
        } else if (this.state.type == 'ele') {
            this.setState({
                titleText: '电流',
                yAxisName: '电流(mA)'
            }, () => {
                this.drawChart();
            })
        }

    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartEleAndTemSearch'));

            let dataZoom = [{
                type: 'inside',
                start: 0,
                end: 100
            }, {
                start: 0,
                end: 100,
                handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                handleSize: '80%',
                handleStyle: {
                    color: '#fff',
                    shadowBlur: 3,
                    shadowColor: 'rgba(0, 0, 0, 0.6)',
                    shadowOffsetX: 2,
                    shadowOffsetY: 2
                }
            }];

            // let markPoint = [];
            // for (let i = 0; i < this.state.chartData.troubleTime.length; i++) {
            //     markPoint.push({
            //         name: '警告',
            //         value: this.state.chartData.troubleValue[i],
            //         xAxis: this.state.chartData.troubleTime[i].replace(' ', '\n'),
            //         yAxis: this.state.chartData.troubleValue[i]
            //     })
            // }

            chart.setOption({
                title: {
                    text: '设备' + this.state.titleText + '变化统计图',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['实际', '阈值'],
                    top: 50
                },
                color: ['#2f4554', '#c23531'],
                grid: {
                    left: '50px',
                    right: '100px',
                    bottom: '40px',
                    top: '100px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                this.state.that.setFullScreen(opts);
                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.time.map(function (str) {
                        return str.replace(' ', '\n')
                    }),
                    // axisLine: { onZero: false }, 年月日换行
                },
                yAxis: {
                    name: this.state.yAxisName,
                    type: 'value',
                    scale: true,
                },
                dataZoom: dataZoom,
                series: [{
                    name: '实际',
                    type: 'line',
                    smooth: true,
                    symbol: 'none',
                    data: this.state.chartData.data,
                    markLine: {
                        data: [
                            {
                                type: 'average',
                                name: '平均值',
                                label: {
                                    normal: {
                                        position: 'end',
                                        formatter: '平均值:{c}',
                                        color: '#d48265'
                                    },
                                },
                                lineStyle: {
                                    color: '#d48265'
                                }
                            }, [{
                                symbol: 'none',
                                x: '90%',
                                yAxis: 'max'
                            }, {
                                symbol: 'circle',
                                label: {
                                    normal: {
                                        position: 'start',
                                        formatter: '最大值',
                                        color: '#c23531'
                                    },
                                },
                                lineStyle: {
                                    color: '#c23531'
                                },
                                type: 'max',
                                name: '最大值',
                            }], [{
                                symbol: 'none',
                                x: '90%',
                                yAxis: 'min'
                            }, {
                                symbol: 'circle',
                                label: {
                                    normal: {
                                        position: 'start',
                                        formatter: '最小值',
                                        color: '#91c7ae'
                                    },
                                },
                                lineStyle: {
                                    color: '#91c7ae'
                                },
                                type: 'min',
                                name: '最小值',
                            }]
                        ]
                    },
                }, {
                    name: '阈值',
                    type: 'line',
                    symbol: 'none',
                    smooth: true,
                    data: this.state.chartData.thresHold,
                    // markPoint: {
                    //     data: markPoint
                    // },
                }]

            });
            window.onresize = chart.resize;
        }
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartEleAndTemSearch' style={chartStyle} />)
    }
}

class MonitorTable extends Component {
    constructor(props) {
        super(props);

        this.state = {
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: false,
            filteredInfo: null,
            sortedInfo: null,
            data: [],
            // searchText: '',
            columnData: [],
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getRecentDeviceInfoApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                // console.log(res);
                for (let key in res.data.data) {
                    columnData.push({
                        nowElectric: res.data.data[key].nowElectric,
                        address: key,
                        name: res.data.data[key].name,
                        nowTemperature: res.data.data[key].nowTemperature,
                        electricThreshold: res.data.data[key].electricThreshold,
                        temperatureThreshold: res.data.data[key].temperatureThreshold,
                    });
                }
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    handleJump = (type, record) => {
        this.props.history.push({ pathname: "/electricityInquiry", state: { record, type } })
        this.props.jump();
    }

    render() {
        const color1 = "blue";
        const color2 = "red";
        const columns = [
            {
                title: "序号",
                width: "10%",
                dataIndex: "key",
                key: "key",
                render: (text, record, index) => `${index + 1}`
            },
            {
                title: "设备号",
                width: "15%",
                dataIndex: "address",
                key: "address"
            },
            {
                title: "设备名称",
                width: "15%",
                dataIndex: "name",
                key: "name",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "温度阈值(单位:℃)",
                width: "15%",
                dataIndex: "temperatureThreshold",
                key: "temperatureThreshold",

            },
            {
                title: "温度(单位:℃)",
                key: "temperature",
                width: "15%",
                render: (text, record) => {
                    let color = undefined;
                    if (record.nowTemperature >= record.temperatureThreshold) {
                        color = color2;
                    } else { color = color1; }
                    return (
                        <div style={{
                            display: "flex",
                            justifyContent: "space-between",
                            paddingRight: "30%",
                        }}>
                            <Tag color={color} width={30}>{record.nowTemperature}</Tag>
                        </div>
                    )
                }
            },
            {
                title: "电流阈值(单位:mA)",
                width: "15%",
                dataIndex: "electricThreshold",
                key: "electricThreshold",
            },
            {
                title: "电流(单位:mA)",
                key: "ele",
                width: "15%",
                render: (text, record) => {
                    let color = undefined;
                    if (record.nowElectric >= record.electricThreshold) {
                        color = color2;
                    } else { color = color1; }
                    return (
                        <div style={{
                            display: "flex",
                            justifyContent: "space-between",
                            paddingRight: "30%",
                        }}>
                            <Tag color={color} width={30}>{record.nowElectric}</Tag>
                        </div>
                    )
                }
            },
        ];
        return (
            <div>
                {/* <div style={{ marginBottom: 16 }}>
                    <ProgressLine refreshData={() => this.refreshData()}></ProgressLine>
                </div> */}
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}

class ProgressLine extends Component {
    constructor(props) {
        super(props);
        this.state = {
            percent: 0,
            animate: null
        };
    }

    componentDidMount() {
        this.refreshData();
        this.increase();
    }

    update() {
        console.log(this.props);
        this.props.refreshData();
    }

    refreshData() {
        this.setState({
            percent: 0,
        }, () => {
            this.increase();
        })

    }

    componentWillUnmount() {
        window.cancelAnimationFrame(this.state.animate);
    }

    increase = () => {
        let animateId;
        const percent = this.state.percent;
        const targetPercent = percent >= 90 ? 100 : percent + 100;
        const speed = (targetPercent - percent) / 10000;
        let start = null;
        const animate = timestamp => {
            if (!start) start = timestamp;
            const progress = timestamp - start;
            const currentProgress = Math.min(parseInt(speed * progress + percent, 10), targetPercent);
            this.setState({
                percent: currentProgress
            });

            if (currentProgress === 100) {
                this.update();
                this.refreshData();
            }

            if (currentProgress < targetPercent) {
                animateId = window.requestAnimationFrame(animate);
            }
        };
        animateId = window.requestAnimationFrame(animate);

        console.log(animateId)
        this.setState({
            animate: animateId
        })
    }

    render() {
        const { percent } = this.state;
        return (
            <Progress percent={percent} showInfo={false} />
        );
    }
}

class ElectricalsafetyDeploy extends Component {
    constructor(props) {
        super(props);
        this.state = {
            msg: "",
            title: "",
            modelVisable: false,
            confirmLoading: false,
            alertVisible: false,
            columnData: [],
            tableLoading: false,
            filteredInfo: null,
            sortedInfo: null,
            unusedImeiList: null,
            IMEI: null,
            Address: null,
            electricalthreshold: null,
            temperaturethreshold: null,
            modelType: null,
        };
    }

    componentDidMount() {
        this.refreshData()
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getDeviceInfoListApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        IEME: item.ieme,
                        name: item.name,
                        temperature: item.temperature,
                        threshold: item.threshold
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getUnDeployDiviceApi()
            .then((res) => {
                const unusedImeiList = []
                res.data.forEach((item, index) => {
                    unusedImeiList.push(item)
                });
                this.setState({
                    unusedImeiList: res.data,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleDelete(id) {
        deleteGpsFireElectricApi(id)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    showModal(type, record) {
        if (type == "add") {
            this.setState({
                modelVisable: true,
                title: "新增设备",
                IMEI: null,
                Address: null,
                electricalthreshold: null,
                temperaturethreshold: null,
                modelType: "add",
            })
        }
        if (type == "update") {

            console.log(record + "ele")
            this.setState({
                modelVisable: true,
                title: "修改设备",
                IMEI: record.IEME,
                Address: record.name,
                electricalthreshold: record.threshold,
                temperaturethreshold: record.temperature,
                modelType: "update",
            })
        }
    }

    handleCancel() {
        this.setState({
            modelVisable: false
        })
    }

    commitForm() {
        this.setState({
            confirmLoading: true,
            tableLoading: true,
        });
        let val = this.refs.deployForm;
        val.validateFields((err, values) => {
            if (!err) {
                if (this.state.modelType == "add") {
                    addGpsFireElectricDeviceApi(sessionStorage.getItem("departmentId"), values)
                        .then(res => {
                            if (res.data == "suceess") {
                                message.success("新增设备成功");
                                this.handleCancel(); //关闭模态框
                                this.refreshData();
                            } else if (res.data == "contained") {
                                message.error("设备号或地址已存在！");
                            } else {
                                message.error("新增失败，请检查填写情况");
                            }
                            this.setState({
                                confirmLoading: false,
                                tableLoading: false,
                            });
                        })
                        .catch((e) => {
                            if (e.response) {
                                //请求已发出，服务器返回状态码不是2xx。
                                console.info(e.response.data)
                                console.info(e.response.status)
                                console.info(e.response.headers)
                            } else if (e.request) {
                                // 请求已发出，但没有收到响应
                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                // 在node中是一个http.ClientRequest实例
                                console.info(e.request)
                            } else {
                                //发送请求时异常，捕捉到错误
                                console.info('error', e.message)
                            }
                            console.info(e.config)
                        });
                }
                else {
                    updateGpsFireElectricDeviceApi(sessionStorage.getItem("departmentId"), values)
                        .then(res => {
                            if (res.data == "success") {
                                message.success("修改成功！");
                                this.handleCancel(); //关闭模态框
                                this.refreshData();
                            } else {
                                message.error("修改失败，请检查填写是否重复");
                            }
                            this.setState({
                                confirmLoading: false,
                                tableLoading: false,
                            });
                        })
                        .catch((e) => {
                            if (e.response) {
                                //请求已发出，服务器返回状态码不是2xx。
                                console.info(e.response.data)
                                console.info(e.response.status)
                                console.info(e.response.headers)
                            } else if (e.request) {
                                // 请求已发出，但没有收到响应
                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                // 在node中是一个http.ClientRequest实例
                                console.info(e.request)
                            } else {
                                //发送请求时异常，捕捉到错误
                                console.info('error', e.message)
                            }
                            console.info(e.config)
                        });
                }
            }
        })
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const userColumns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "设备号IMEI",
                dataIndex: "IEME",
                key: "IEME"
            },
            {
                title: "设备地址",
                dataIndex: "name",
                key: "name",
            },
            {
                title: "温度阈值(℃)",
                dataIndex: "temperature",
                key: "temperature"
            },
            {
                title: "电流阈值(mA)",
                dataIndex: "threshold",
                key: "threshold",
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a href="javascript:;" onClick={() => this.showModal("update", record)}>修改</a>
                        <Divider type="vertical" />
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDelete(record.id)}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }
        ];
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" onClick={() => this.showModal("add")} size="large">
                        <Icon type="user-add" />新增设备
                    </Button>
                    <Modal
                        title={this.state.title}
                        destroyOnClose={true}
                        visible={this.state.modelVisable}
                        onCancel={() => this.handleCancel()}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={() => this.commitForm()}>提交</Button>
                        ]}
                    >
                        <DepolyForm ref="deployForm" temperaturethreshold={this.state.temperaturethreshold} electricalthreshold={this.state.electricalthreshold} IMEI={this.state.IMEI} Address={this.state.Address} unusedImeiList={this.state.unusedImeiList} />
                    </Modal>
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={userColumns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        );
    }
}

class depolyForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            IMEIList: this.props.unusedImeiList == undefined ? undefined : this.props.unusedImeiList,
            IMEI: this.props.IMEI == undefined ? undefined : this.props.IMEI,
            Address: this.props.Address == undefined ? undefined : this.props.Address,
            electricalthreshold: this.props.electricalthreshold == undefined ? undefined : this.props.electricalthreshold,
            temperaturethreshold: this.props.temperaturethreshold == undefined ? undefined : this.props.temperaturethreshold,
        };
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };
        let IMEIOptions = []
        if (this.state.IMEIList.length > 0) {
            IMEIOptions = this.state.IMEIList.map((d, index) => {
                console.log(d, "++++++++++++++++++++++")
                return (<Option value={d} key={index}>{d}</Option>)
            });
        }
        return (
            <Form>
                <FormItem
                    label='设备号IMEI'
                    {...formItemLayout}
                >
                    {getFieldDecorator("IMEI", {
                        initialValue: this.state.IMEI,
                        rules: [{
                            required: true,
                            message: "请选择设备号!"
                        }]
                    })(
                        <Select
                            mode="single"
                            size="large"
                            placeholder="选择设备号">
                            {IMEIOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='设备地址'
                    {...formItemLayout}>
                    {getFieldDecorator("address", {
                        initialValue: this.state.Address,
                        rules: [{
                            required: true,
                            message: " 请输入地址!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="question-circle-o" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="设备地址"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='温度阈值(℃)'
                    {...formItemLayout}>
                    {getFieldDecorator("temperaturethreshold", {
                        initialValue: this.state.temperaturethreshold,
                        rules: [{
                            required: true,
                            message: "请输入温度阈值!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="温度阈值"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='电流阈值(mA)'
                    {...formItemLayout}>
                    {getFieldDecorator("electricalthreshold", {
                        initialValue: this.state.electricalthreshold,
                        rules: [{
                            required: true,
                            message: "请输入电流阈值!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="电流阈值"
                        />
                    )}
                </FormItem>
            </Form>
        )
    }
}
const DepolyForm = Form.create()(depolyForm);

class smokeDevice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            msg: "", //提交失败时的提示语
            tableLoading: true,
            tableData: [],

            deviceIdArr: [],
            deviceNameArr: [],
            deviceAddressArr: [],

            filteredInfo: null,
            sortedInfo: null,
            // searchText: '',
            isSearch: false,
            searchChartLoading: false,
            chartSearchData: {
                timestamp: [],
                time: []
            },

            deviceStatusArr: [{
                value: '00',
                text: '正常'
            }, {
                value: '01',
                text: '烟雾报警'
            }, {
                value: '02',
                text: '防拆异常'
            }, {
                value: '03',
                text: '电压异常（电压低于2.9V）'
            }, {
                value: '04',
                text: '通信故障'
            }, {
                value: '05',
                text: '设备故障'
            }, {
                value: '06',
                text: '其他故障'
            }],

            detailVisible: false,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let tableData = [];
        let deviceIdArr = [];
        let deviceNameArr = [];
        let deviceAddressArr = [];
        getAllSmokeDeviceRecordBySchoolIdApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.table.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    tableData.push({
                        key: index + 1,
                        deviceId: item.deviceId,
                        name: item.name,
                        address: item.address,
                        deviceStatus: item.deviceStatus,
                        fireAlarm: item.fireAlarm,
                        smokeConc: item.smokeConc,
                        envTemp: item.envTemp,
                        batteryVoltage: item.batteryVoltage,
                        tamper: item.tamper,
                        timestamp: item.timestamp,
                    });
                    deviceIdArr.push(item.deviceId);
                    deviceNameArr.push(item.name);
                    deviceAddressArr.push(item.address);
                });
                this.setState({
                    tableData: tableData,
                    deviceIdArr: deviceIdArr,
                    deviceNameArr: deviceNameArr,
                    deviceAddressArr: deviceAddressArr,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            values.address = values.address || undefined;
            values.deviceId = values.deviceId || undefined;
            values.name = values.name || undefined;

            console.log('Received values of form: ', values);
            if (values.address == undefined && values.deviceId == undefined
                && (values.deviceStatus == undefined || values.deviceStatus.length == 0)
                && values.fireAlarm == undefined && values.name == undefined && values.smokeConc.numberLarge === ''
                && values.smokeConc.numberLittle === '' && values.tamper == undefined && values.timestamp == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true,
                    searchChartLoading: true,
                    isSearch: true,
                });
                if (values.timestamp != undefined) {
                    values.timePre = values.timestamp[0].format('YYYY-MM-DD');
                    values.timeAfter = values.timestamp[1].format('YYYY-MM-DD');
                }

                if (values.deviceStatus != undefined && values.deviceStatus.length == 0) {
                    values.deviceStatus = undefined;
                }

                getSearchSmokeDeviceRecordApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        let tableData = [];
                        res.data.table.forEach((item, index) => {
                            //console.log("getAllUser", item);
                            tableData.push({
                                key: index + 1,
                                deviceId: item.deviceId,
                                name: item.name,
                                address: item.address,
                                deviceStatus: item.deviceStatus,
                                fireAlarm: item.fireAlarm,
                                smokeConc: item.smokeConc,
                                envTemp: item.envTemp,
                                batteryVoltage: item.batteryVoltage,
                                tamper: item.tamper,
                                timestamp: item.timestamp,
                            });
                        });

                        this.setState({
                            tableData: tableData,
                            tableLoading: false,
                            alertVisible: false,
                            chartSearchData: res.data.echarts,
                            searchChartLoading: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        });
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
        });
        this.refreshData();
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    showDetailDrawer = (deviceId, deviceName, deviceAddress) => {
        this.setState({
            detailVisible: true,
            currentDeviceId: deviceId,
            currentDeviceName: deviceName,
            currentDeviceAddress: deviceAddress,
        })
    }

    handleDetailCancel = () => {
        this.setState({
            detailVisible: false,
        })
    }

    tamperValidator = (rule, value, callback) => {
        // const { getFieldValue } = this.props.form;
        if (value.numberLittle != '' && value.numberLarge != ''
            && value.numberLittle >= value.numberLarge) {
            callback('区间填写错误！')
        }
        // 必须总是返回一个 callback，否则 validateFields 无法响应
        callback();
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }


    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        let keyWidth = undefined;
        let deviceIdWidth = undefined;
        let nameWidth = undefined;
        let addressWidth = undefined;
        let deviceStatusWidth = undefined;
        let fireAlarmWidth = undefined;
        let smokeConcWidth = undefined;
        let envTempWidth = undefined;
        let batteryVoltageWidth = undefined;
        let tamperConcWidth = undefined;
        let timestampWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            deviceIdWidth = 95;
            nameWidth = 100;
            addressWidth = 90;
            deviceStatusWidth = 80;
            fireAlarmWidth = 90;
            smokeConcWidth = 80;
            envTempWidth = 80;
            batteryVoltageWidth = 60;
            tamperConcWidth = 90;
            timestampWidth = 120;
        }

        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "设备编号",
            dataIndex: "deviceId",
            key: "deviceId",
            width: deviceIdWidth,
        }, {
            title: "设备名称",
            dataIndex: "name",
            key: "name",
            width: nameWidth,
        }, {
            title: '设备地址',
            dataIndex: 'address',
            key: 'address',
            width: addressWidth
        }, {
            title: '设备状态',
            dataIndex: 'deviceStatus',
            key: 'deviceStatus',
            width: deviceStatusWidth,
            filters: this.state.deviceStatusArr,
            onFilter: (value, record) => record.deviceStatus.indexOf(value) === 0,
            render: (text, record) => {
                if (text == '00') {
                    return (<Tag color={'green'}>正常</Tag>)
                } else if (text == '01') {
                    return (<Tag color={'red'}>烟雾报警</Tag>)
                } else if (text == '02') {
                    return (<Tag color={'red'}>防拆异常</Tag>)
                } else if (text == '03') {
                    return (<Tag color={'red'}>电压异常</Tag>)
                } else if (text == '04') {
                    return (<Tag color={'red'}>通信故障</Tag>)
                } else if (text == '05') {
                    return (<Tag color={'red'}>设备故障</Tag>)
                } else if (text == '06') {
                    return (<Tag color={'red'}>其他故障</Tag>)
                }
            },
        }, {
            title: '火警状态',
            dataIndex: 'fireAlarm',
            key: 'fireAlarm',
            width: fireAlarmWidth,
            render: (text, record) => {
                if (text == 0) {
                    return '非火警';
                } else if (text == 1) {
                    return '火警';
                }
            },
        }, {
            title: '烟雾浓度',
            dataIndex: 'smokeConc',
            key: 'smokeConc',
            width: smokeConcWidth,
            render: (text, record) => {
                if (record.timestamp != 0) {
                    return (<Tag color={'orange'}>{text} mg/m³</Tag>);
                } else {
                    if (text == 0) {
                        return (
                            <Tag
                                style={{ textAlign: 'center' }}
                                color={'green'}>
                                正常{winWidth < 1500 ? <br></br> : null}无反馈
                            </Tag>
                        );
                    } else {
                        return (<Tag color={'orange'}>{text} mg/m³</Tag>);
                    }
                }
            },
        }, {
            title: '环境温度',
            dataIndex: 'envTemp',
            key: 'envTemp',
            width: envTempWidth,
            render: (text, record) => {
                if (record.timestamp != 0) {
                    return text + ' ℃';
                } else {
                    if (text == 0) {
                        return (
                            <Tag
                                style={{ textAlign: 'center' }}
                                color={'green'}>
                                正常{winWidth < 1500 ? <br></br> : null}无反馈
                            </Tag>
                        );
                    } else {
                        return text + ' ℃';
                    }
                }
            },
        }, {
            title: '工作电压',
            dataIndex: 'batteryVoltage',
            key: 'batteryVoltage',
            width: batteryVoltageWidth,
            render: (text, record) => {
                return text + ' V';
            },
        }, {
            title: '防拆情况',
            dataIndex: 'tamper',
            key: 'tamper',
            width: tamperConcWidth,
            render: (text, record) => {
                if (text == 0) {
                    return (<Tag color={'green'}>正常</Tag>);
                } else if (text == 1) {
                    return (
                        <Tag
                            style={{ textAlign: 'center' }}
                            color={'red'}>
                            防拆盖{winWidth < 1500 ? <br></br> : null}脱离
                        </Tag>
                    )
                }
            },
        }, {
            title: '最近反馈时间',
            dataIndex: 'timestamp',
            key: 'timestamp',
            width: timestampWidth,
            sorter: (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
            sortOrder: sortedInfo.columnKey === 'timestamp' && sortedInfo.order,
            render: (text, record) => {
                return text == '0' ? (
                    <Tag
                        style={{ textAlign: 'center' }}
                        color={'green'}>
                        正常{winWidth < 1500 ? <br></br> : null}无反馈
                    </Tag>
                ) : text;
            }
        }, {
            title: "操作详情",
            key: "action",
            render: (text, record) => {
                return (
                    <span>
                        <a
                            href="javascript:;"
                            onClick={this.showDetailDrawer.bind(this,
                                record.deviceId, record.name, record.address)}>
                            历史反馈
                        </a>
                    </span>
                )
            }
        }];

        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        let deviceStatusOptions;
        if (this.state.deviceStatusArr.length != 0) {
            deviceStatusOptions = this.state.deviceStatusArr.map((d, index) =>
                <Option value={d.value} key={index}>{d.text}</Option>
            );
        }

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="设备编号"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deviceId", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.deviceIdArr}
                                        placeholder="请输入设备编号"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="设备名称"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("name", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.deviceNameArr}
                                        placeholder="请输入设备名称"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="设备地址"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("address", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.deviceAddressArr}
                                        placeholder="请输入设备地址"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="设备状态"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deviceStatus", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择设备状态(可多选)">
                                        {deviceStatusOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="火警状态"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("fireAlarm", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择火警状态">
                                        <Option value={1}>火警</Option>
                                        <Option value={2}>非火警</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="烟雾浓度"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("smokeConc", {
                                    initialValue: { numberLittle: '', numberLarge: '' },
                                    rules: [{
                                        required: false,
                                    }, {
                                        validator: (rule, value, callback) => this.tamperValidator(rule, value, callback)
                                    }],
                                    validateTrigger: 'onSubmit'
                                })(
                                    <InputComp />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="防拆情况"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("tamper", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择防拆情况">
                                        <Option value={0}>正常</Option>
                                        <Option value={1}>防拆盖脱离</Option>
                                    </Select>
                                )}

                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="反馈时间"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("timestamp", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                {this.state.isSearch ?
                    (
                        <div style={{
                            marginBottom: 16,
                            padding: 16,
                            width: '100%',
                            height: 300,
                            border: '1px solid',
                            borderColor: '#f5f5f5'
                        }}>
                            <Skeleton loading={this.state.searchChartLoading} active>
                                {this.state.chartSearchData.timestamp.length == 0 ? (
                                    <Empty
                                        image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                                        imageStyle={{
                                            marginTop: 60,
                                        }}
                                        description={
                                            <span style={{ color: '#7a7a7a' }}>
                                                未接受到数据，请按照条件搜索以展示可视化图表
                                            </span>
                                        }
                                    />
                                ) : (
                                    <ChartSmokeSearch
                                        that={this}
                                        chartData={this.state.chartSearchData} />
                                )}
                            </Skeleton>
                        </div>
                    ) : null
                }
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={800}
                    title={'设备历史反馈记录'}
                    visible={this.state.detailVisible}
                    onClose={this.handleDetailCancel.bind(this)}
                    destroyOnClose={true}
                    closable
                >
                    <SmokeDeviceDetail
                        currentDeviceId={this.state.currentDeviceId}
                        currentDeviceName={this.state.currentDeviceName}
                        currentDeviceAddress={this.state.currentDeviceAddress}
                        thar={this} />
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                            onClick={this.handleDetailCancel.bind(this)}>关闭</Button>
                    </div>
                </Drawer>

                <Table
                    dataSource={this.state.tableData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.tableData.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={'烟感设备历史反馈次数统计图'}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />

                </Modal>
            </div>
        )
    }

}
const SmokeDevice = Form.create()(smokeDevice);

class InputComp extends Component {
    static getDerivedStateFromProps(nextProps) {
        if ('value' in nextProps) {
            return {
                ...(nextProps.value || {})
            }
        }
        return null
    }
    constructor(props) {
        super(props)
        const value = props.value || {}
        this.state = {
            numberLittle: value.numberLittle || '',
            numberLarge: value.numberLarge || '',
        }
    }
    numberLittleChange = e => {
        const numberLittle = parseInt(e.target.value)
        if (isNaN(numberLittle) || numberLittle == undefined) {
            this.setState({ numberLittle: '' });
            this.triggerChange({ numberLittle: '' });
            return 0;
        }
        if (!('value' in this.props)) {
            this.setState({ numberLittle });
        }
        this.triggerChange({ numberLittle });
    }
    numberLargeChange = e => {
        const numberLarge = parseInt(e.target.value)
        if (isNaN(numberLarge) || numberLarge == undefined) {
            this.setState({ numberLarge: '' });
            return 0;
        }
        if (!('value' in this.props)) {
            this.setState({ numberLarge });
        }
        this.triggerChange({ numberLarge });
    }
    triggerChange = changedValue => {
        const { onChange } = this.props
        if (onChange) {
            onChange({
                ...this.state,
                ...changedValue
            })
        }
    }
    render() {
        const { numberLittle, numberLarge } = this.state;
        return (
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Input
                    style={{
                        flex: 4.7,
                        borderRight: 0,
                        borderRadius: '4px 0 0 4px',
                    }}
                    onChange={this.numberLittleChange}
                    value={numberLittle}
                    suffix="mg/m³"
                    placeholder="0"
                />
                <Input
                    style={{
                        flex: 0.6,
                        borderLeft: 0,
                        borderRight: 0,
                        pointerEvents: 'none',
                        backgroundColor: '#fff',
                        textAlign: 'center',
                        borderRadius: 0,
                    }}
                    placeholder="~"
                    disabled
                />
                <Input
                    style={{
                        flex: 4.7,
                        borderLeft: 0,
                        borderRadius: '0 4px 4px 0',
                    }}
                    onChange={this.numberLargeChange}
                    value={numberLarge}
                    suffix="mg/m³"
                    placeholder="∞"
                />
            </div>
        )
    }
}

class SmokeDeviceDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentDeviceId: props.currentDeviceId,
            currentDeviceName: props.currentDeviceName,
            currentDeviceAddress: props.currentDeviceAddress,
            that: props.that,

            data: [],
            loading: false,

            currentListData: [],
            scrollLoading: false,
            hasMore: true,

        };
        //console.log('currentInspectPlanIds', props.currentInspectPlanIds)
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            confirmLoading: true,
        })
        getSingleSmokeDeviceRecordApi(parseInt(sessionStorage.getItem("departmentId")), this.state.currentDeviceId)
            .then((res) => {
                let data = [];
                let currentListData = [];
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    data.push({
                        deviceStatus: item.deviceStatus,
                        fireAlarm: item.fireAlarm,
                        smokeConc: item.smokeConc,
                        envTemp: item.envTemp,
                        batteryVoltage: item.batteryVoltage,
                        tamper: item.tamper,
                        timestamp: item.timestamp,
                    });
                });

                if (data.length > 5) {
                    currentListData = data.slice(0, 5);
                } else {
                    currentListData = data.slice(0, data.length);
                }

                this.setState({
                    data: data,
                    currentListData: currentListData,
                    loading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleInfiniteOnLoad = () => {
        this.setState({
            scrollLoading: true,
        }, () => {
            let data = [...this.state.data];
            let currentListData = [...this.state.currentListData];
            setTimeout(() => {
                if (data.length == currentListData.length) {
                    message.info('已经到底了~');
                    this.setState({
                        hasMore: false,
                        scrollLoading: false,
                    });
                    return;
                } else if (data.length - currentListData.length <= 5) {
                    this.setState({
                        currentListData: data,
                        scrollLoading: false,
                        hasMore: false,
                    })
                } else {
                    this.setState({
                        currentListData: currentListData.concat(...[data.slice(currentListData.length, currentListData.length + 5)]),
                        scrollLoading: false,
                    });
                }
            }, 500);
        });
    }

    render() {
        let listData = [];
        if (this.state.currentListData.length > 0) {
            listData = this.state.currentListData.map((d, index) => {
                let deviceStatusObject = {
                    '00': (<Tag color='green'>正常</Tag>),
                    '01': (<Tag color='red'>烟雾报警</Tag>),
                    '02': (<Tag color='red'>防拆异常</Tag>),
                    '03': (<Tag color='red'>电压异常</Tag>),
                    '04': (<Tag color='red'>通信故障</Tag>),
                    '05': (<Tag color='red'>设备故障</Tag>),
                    '06': (<Tag color='red'>其他故障</Tag>),
                };

                let fireAlarmObject = {
                    0: '非火警',
                    1: '火警'
                };

                let tamperObject = {
                    0: (<Tag color='green'>正常</Tag>),
                    1: (<Tag color='red'>防拆盖脱离</Tag>)
                }

                let singleData = [{
                    title: '设备状态',
                    value: deviceStatusObject[d.deviceStatus],
                }, {
                    title: '火警状态',
                    value: fireAlarmObject[d.fireAlarm],
                }, {
                    title: '烟雾浓度',
                    value: d.smokeConc + ' mg/m³',
                }, {
                    title: '环境温度',
                    value: d.envTemp + ' ℃',
                }, {
                    title: '工作电压',
                    value: d.batteryVoltage + ' V',
                }, {
                    title: '防拆情况',
                    value: tamperObject[d.tamper],
                }];

                return (
                    <List
                        grid={{ gutter: 4, column: 6 }}
                        dataSource={singleData}
                        renderItem={item => (
                            <List.Item
                                style={{ marginBottom: 0 }}>
                                <Card
                                    className='innerConditionCard'
                                    style={{ margin: 0 }}
                                    title={item.title}
                                    size="small">
                                    {item.value}
                                </Card>
                            </List.Item>
                        )}
                    />
                )
            });
        }

        let headData = [{
            title: '设备编号',
            value: this.state.currentDeviceId
        }, {
            title: '设备名称',
            value: this.state.currentDeviceName
        }, {
            title: '设备地址',
            value: this.state.currentDeviceAddress
        }]

        return (
            <div>
                <List
                    grid={{ gutter: 8, column: 3 }}
                    dataSource={headData}
                    renderItem={item => (
                        <List.Item>
                            <Card
                                className='conditionCard'
                                title={item.title}
                                size='small'
                            >{item.value}</Card>
                        </List.Item>
                    )}
                />
                <Divider>数据列表</Divider>

                {this.state.currentListData.length == 0 ? (<Empty />) : (
                    <List
                        grid={{ column: 1 }}
                        dataSource={listData}
                        renderItem={(item, index) => (
                            <List.Item>
                                <Card
                                    headStyle={{ borderBottom: '1.5px solid #ccc' }}
                                    className='conditionCard'
                                    title={this.state.data[index].timestamp}
                                    size='small'
                                    style={{ borderRadius: '10px', border: '1.5px solid #ccc' }}>
                                    {item}
                                </Card>
                            </List.Item>
                        )}>
                        <div style={{ textAlign: 'center' }}>
                            {this.state.scrollLoading ? (<Spin size="large" />) : (
                                this.state.hasMore ? (
                                    <Button onClick={this.handleInfiniteOnLoad}>加载更多</Button>
                                ) : (<span style={{ color: '#999999' }}>数据加载完毕</span>)
                            )}
                        </div>
                    </List>
                )}
            </div>
        )
    }
}

class ChartSmokeSearch extends Component {
    constructor(props) {
        super(props);

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;

        this.state = {
            chartData: props.chartData,
            that: props.that,
            winWidth: winWidth,
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.chartData) != JSON.stringify(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that,
            }, () => {
                this.drawChart();
            })
        }
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('ChartSmokeSearch'));

            let dataZoom;

            if (this.state.chartData.timestamp.length <= 30) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    start: (this.state.chartData.timestamp.length - 30) / this.state.chartData.timestamp.length * 100,
                    end: 100,
                }, {
                    start: (this.state.chartData.timestamp.length - 30) / this.state.chartData.timestamp.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }

            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['反馈次数'],
                    top: 50
                },
                color: ['#2f4554', '#c23531'],
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        // restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                // console.log(this.state)
                                this.state.that.setFullScreen(opts);
                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.timestamp,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '次数',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '上报数',
                    type: 'line',
                    data: this.state.chartData.times,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='ChartSmokeSearch' style={chartStyle} />)
    }
}


class upAndDownDevice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            tableData: [],

            filteredInfo: null,
            sortedInfo: null,
            // searchText: '',
            isSearch: false,

            chartData: {
                d: [],
                startTime: undefined
            },
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let tableData = [];
        getUpAndDownDeviceMessageApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.table.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    tableData.push({
                        key: index + 1,
                        deviceId: item.deviceId,
                        name: item.name,
                        address: item.address,
                        position: item.position,
                        datetime: item.datetime,
                        alertType: item.alert_type,
                    });
                });
                this.setState({
                    tableData: tableData,
                    chartData: res.data.chartData,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
        }, {
            title: "设备编号",
            dataIndex: "deviceId",
            key: "deviceId",
        }, {
            title: "设备名称",
            dataIndex: "name",
            key: "name",
        }, {
            title: '设备地址',
            dataIndex: 'address',
            key: 'address',
        }, {
            title: '升降状态',
            dataIndex: 'position',
            key: 'position',
            render: (text, record) => {
                let option = {
                    'FF': '顶部',
                    '00': '底部',
                    '55': '中间'
                };
                return option[text];
            }
        }, {
            title: '最近记录时间',
            dataIndex: 'datetime',
            key: 'datetime',
            sorter: (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
            sortOrder: sortedInfo.columnKey === 'datetime' && sortedInfo.order,
        }, {
            title: '报警状态',
            dataIndex: 'alertType',
            key: 'alertType',
        }];

        return (
            <div style={{ marginBottom: 16 }}>
                <div style={{
                    marginBottom: 16,
                    padding: 16,
                    width: '100%',
                    height: 300,
                    border: '1px solid',
                    borderColor: '#f5f5f5'
                }}>
                    <Skeleton loading={this.state.tableLoading} active>
                        {this.state.chartData.d.length == 0 ? (
                            <Empty
                                image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                                imageStyle={{
                                    marginTop: 60,
                                }}
                                description={
                                    <span style={{ color: '#7a7a7a' }}>
                                        暂无数据
                                    </span>
                                }
                            />
                        ) : (
                            <ChartUpAndDownDevice
                                that={this}
                                chartData={this.state.chartData} />
                        )}
                    </Skeleton>
                </div>
                <Table
                    dataSource={this.state.tableData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.tableData.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={'防撞柱设备统计图'}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />

                </Modal>
            </div>
        )
    }

}
const UpAndDownDevice = Form.create()(upAndDownDevice);

class ChartUpAndDownDevice extends Component {
    constructor(props) {
        super(props);

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;

        this.state = {
            chartData: props.chartData,
            that: props.that,
            winWidth: winWidth,
            // chartData: {
            //     d: [{
            //         deviceId: '1',
            //         time: [[1574661600000, 1574662200000], [1574662200000, 1574662500000], [1574662500000, 1574662800000], [1574662800000, 1574663400000], [1574663400000, 1574664600000], [1574664600000, 1574665800000]],
            //         position: ['FF', '55', '00', '55', 'FF', '55'],
            //     }, {
            //         deviceId: '2',
            //         time: [[1574661600000, 1574662200000], [1574662200000, 1574662500000], [1574662500000, 1574662800000], [1574662800000, 1574663400000], [1574663400000, 1574664600000], [1574664600000, 1574665800000]],
            //         position: ['FF', '55', '00', '55', 'FF', '55'],
            //     }, {
            //         deviceId: '3',
            //         time: [[1574661600000, 1574662200000], [1574662200000, 1574662500000], [1574662500000, 1574662800000], [1574662800000, 1574663400000], [1574663400000, 1574664600000], [1574664600000, 1574665800000]],
            //         position: ['FF', '55', '00', '55', 'FF', '55'],
            //     }],
            //     startTime: 1574661600000,
            // },

            typesColor: {
                'FF': '#7b9ce1', //蓝
                '00': '#bd6d6c', //red
                '55': '#75d874', //green
            },

            types: {
                'FF': '顶部',
                '00': '底部',
                '55': '中间',
            },
        };
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {

            console.log("进入升降柱图表里来=================================")
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartUpAndDownDevice'));

            let dataZoom;

            if (Math.floor(new Date().getTime() - this.state.chartData.startTime) / (24 * 3600 * 1000) <= 3) {
                dataZoom = [{
                    type: 'inside',
                    filterMode: 'weakFilter',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    },
                    filterMode: 'weakFilter',
                    labelFormatter: ''
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    filterMode: 'weakFilter',
                    start: (new Date().getTime() - (3 * 24 * 3600 * 1000) - this.state.chartData.startTime) /
                        (new Date().getTime() - this.state.chartData.startTime) * 100,
                    end: 100,
                }, {
                    start: (new Date().getTime() - (3 * 24 * 3600 * 1000) - this.state.chartData.startTime) /
                        (new Date().getTime() - this.state.chartData.startTime) * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    },
                    filterMode: 'weakFilter',
                    labelFormatter: ''
                }];
            }

            let data = [];
            let categories = [];

            for (let i = 0; i < this.state.chartData.d.length; i++) {
                categories.push(this.state.chartData.d[i].name);
                for (let j = 0; j < this.state.chartData.d[i].position.length; j++) {
                    data.push({
                        name: this.state.chartData.d[i].name,
                        value: [
                            i,
                            this.state.chartData.d[i].time[j][0],
                            this.state.chartData.d[i].time[j][1],
                            this.state.types[this.state.chartData.d[i].position[j]],
                        ],
                        itemStyle: {
                            normal: {
                                color: this.state.typesColor[this.state.chartData.d[i].position[j]]
                            }
                        }
                    });
                }
            }

            chart.setOption({
                title: {
                    text: '防撞柱状态变化展示图',
                    left: 'center'
                },
                tooltip: {
                    formatter: function (params) {
                        return params.marker + '<br>'
                            + '时间段: ' + moment(params.value[1]).format("YYYY-MM-DD HH:mm:ss") + ' ~ '
                            + moment(params.value[2]).format("HH:mm:ss") + '<br>'
                            + '状态: ' + params.value[3];
                    }
                },
                color: ['#7b9ce1', '#bd6d6c', '#75d874'],
                legend: {
                    data: ['顶部', '底部', '中间'],
                    top: 30,
                    selectedMode: false,
                },
                grid: {
                    left: '30px',
                    right: '50px',
                    bottom: '40px',
                    top: '50px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                this.state.that.setFullScreen(opts);
                            }
                        }
                    }
                },
                xAxis: {
                    min: this.state.chartData.startTime,
                    scale: true,
                    axisLabel: {
                        formatter: function (val) {
                            return moment(val).format("YYYY-MM-DD[\n]HH:mm:ss");
                        }
                    }
                },
                yAxis: {
                    name: '设备名称',
                    data: categories
                },
                dataZoom: dataZoom,
                series: [{
                    type: 'custom',
                    name: '顶部',
                    renderItem: (params, api) => this.renderItem(params, api),
                    encode: {
                        x: [1, 2],
                        y: 0
                    },
                    data: data,
                },
                {
                    type: 'custom',
                    name: '底部',
                    renderItem: (params, api) => this.renderItem(params, api),
                    encode: {
                        x: [1, 2],
                        y: 0
                    },
                    data: data,
                }, {
                    type: 'custom',
                    name: '中间',
                    renderItem: (params, api) => this.renderItem(params, api),
                    encode: {
                        x: [1, 2],
                        y: 0
                    },
                    data: data,
                }],
            });
            window.onresize = chart.resize;
        }
    }

    renderItem = (params, api) => {
        let categoryIndex = api.value(0);
        let start = api.coord([api.value(1), categoryIndex]);
        let end = api.coord([api.value(2), categoryIndex]);
        let height = 40;

        let rectShape = echarts.graphic.clipRectByRect({
            x: start[0],
            y: start[1] - height / 2,
            width: end[0] - start[0],
            height: height
        }, {
            x: params.coordSys.x,
            y: params.coordSys.y,
            width: params.coordSys.width,
            height: params.coordSys.height
        });
        return rectShape && {
            type: 'rect',
            shape: rectShape,
            style: api.style()
        };
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartUpAndDownDevice' style={chartStyle} />)
    }
}

// class FaceRecord extends Component {
//     constructor(props) {
//         super(props);
//         this.state = {
//             tableData: [],
//             tableLoading: false,
//         }
//     }

//     componentDidMount() {
//         this.setState({
//             tableLoading: true
//         });
//         let tableData = [];
//         getFaceRecordByDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
//             .then((res) => {
//                 res.data.forEach((item, index) => {
//                     //console.log("getAllUser", item);
//                     tableData.push({
//                         key: index + 1,
//                         devicename: item.devicename,
//                         personId: item.personId,
//                         name: item.name,
//                         usertype: item.usertype,
//                         employer: item.employer,
//                         date: item.date,
//                         facerecordtype: item.type,
//                     });
//                 });
//                 this.setState({
//                     tableData: tableData,
//                     tableLoading: false,
//                 });
//             })
//             .catch((e) => {
//                 if (e.response) {
//                     //请求已发出，服务器返回状态码不是2xx。
//                     console.info(e.response.data)
//                     console.info(e.response.status)
//                     console.info(e.response.headers)
//                 } else if (e.request) {
//                     // 请求已发出，但没有收到响应
//                     // e.request 在浏览器里是一个XMLHttpRequest实例，
//                     // 在node中是一个http.ClientRequest实例
//                     console.info(e.request)
//                 } else {
//                     //发送请求时异常，捕捉到错误
//                     console.info('error', e.message)
//                 }
//                 console.info(e.config)
//             });
//     }

//     render() {

//         const columns = [{
//             title: "序号",
//             dataIndex: "key",
//             key: "key",
//         }, {
//             title: "设备名称",
//             dataIndex: "devicename",
//             key: "devicename",
//         }, {
//             title: '识别人编号',
//             dataIndex: 'personId',
//             key: 'personId',
//         }, {
//             title: '识别人姓名',
//             dataIndex: 'name',
//             key: 'name',
//         }, {
//             title: '识别人类型',
//             dataIndex: 'usertype',
//             key: 'usertype',
//             render: (text, record) => {
//                 let option = {
//                     '1': '学生',
//                     '2': '教师',
//                     '0': 'Stranger'
//                 };
//                 return option[text];
//             }
//         }, {
//             title: '识别人单位',
//             dataIndex: 'employer',
//             key: 'employer',
//         }, {
//             title: '识别时间',
//             dataIndex: 'date',
//             key: 'date',
//         }, {
//             title: '识别类型',
//             dataIndex: 'facerecordtype',
//             key: 'facerecordtype',
//             render: (text, record) => {
//                 let option = {
//                     'face_0': '刷脸识别',
//                     'face_1': '刷脸识别',
//                     'face_2': '刷脸识别',
//                     'card_0': '刷卡识别',
//                     'card_1': '刷卡识别',
//                     'faceAndcard_0': '双重认证',
//                     'faceAndcard_1': '双重认证',
//                     'faceAndcard_2': '双重认证',
//                     'idcard_0': '人证比对',
//                     'idcard_1': '人证比对',
//                     'idcard_2': '人证比对'
//                 };
//                 return option[text];
//             }
//         }]

//         return (
//             <div style={{ marginBottom: 16 }}>
//                 <div style={{
//                     marginBottom: 16,
//                     padding: 16,
//                     width: '100%',
//                     height: 300,
//                     // border: '1px solid',
//                     // borderColor: '#f5f5f5'
//                 }}>
//                     <Table
//                         dataSource={this.state.tableData}
//                         columns={columns}
//                         loading={this.state.tableLoading}
//                         locale={{ emptyText: '暂无数据' }}
//                         rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
//                         pagination={{  //分页
//                             total: this.state.tableData.length, //数据总数量
//                             defaultPageSize: 10, //默认显示几条一页
//                             //pageSize: 10,
//                             showTotal: function (total) {  //设置显示一共几条数据
//                                 return '共 ' + total + ' 条数据';
//                             },
//                             showSizeChanger: true,
//                             showQuickJumper: true,
//                             pageSizeOptions: [5, 10, 20, 30]
//                         }} />

//                 </div>
//             </div>
//         )
//     }
// }

class FaceImageManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            filteredInfo: null,
            sortedInfo: null,
            searchUserNumber: '',
            searchName: '',
            searchEmployer: '',
            tableLoading: false,
            data: [],
            tableData: [],
            imageVisible: false,
            imageUrl: "",
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let tableData = [];
        getFaceImageBasicManageApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    tableData.push({
                        key: index + 1,
                        usernumber: item.personId + '',
                        name: item.name,
                        employer: item.employer,
                        faceimage: item.faceimage,
                        condition: item.unenternum,
                    });
                });
                this.setState({
                    tableData: tableData,
                    tableLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    imageModalCancel() {
        this.setState({
            imageVisible: false,
        });
    }

    checkImage(text) {
        this.setState({
            imageVisible: true,
            imageUrl: text
        });
    }

    forInnerTableChange(FatherKey) {
        let tableData = [...this.state.tableData];
        tableData[FatherKey - 1].condition -= 1
        this.setState({
            tableData: tableData
        }, () => {
            console.log(this.state.tableData, "!!!!!!!!!!")
        })
    }

    handleUpdateFaceImage(record) {
        message.error('本地服务未上线，暂不支持');
    }

    handleDeleteFaceImage(usernumber) {
        message.error('本地服务未上线，暂不支持');
        //     this.setState({
        //         tableLoading: true
        //     });
        //     let tableData = [];
        //     deleteFaceImageApi(parseInt(sessionStorage.getItem("departmentId")), parseInt(usernumber))
        //         .then((res) => {
        //             if (res.data == "success") {
        //                 this.setState({
        //                     tableLoading: false,
        //                 });
        //                 this.refreshData();
        //             } else {
        //                 message.error('删除失败,请稍后再试!');
        //             }
        //         })
        //         .catch((e) => {
        //             if (e.response) {
        //                 //请求已发出，服务器返回状态码不是2xx。
        //                 console.info(e.response.data)
        //                 console.info(e.response.status)
        //                 console.info(e.response.headers)
        //             } else if (e.request) {
        //                 // 请求已发出，但没有收到响应
        //                 // e.request 在浏览器里是一个XMLHttpRequest实例，
        //                 // 在node中是一个http.ClientRequest实例
        //                 console.info(e.request)
        //             } else {
        //                 //发送请求时异常，捕捉到错误
        //                 console.info('error', e.message)
        //             }
        //             console.info(e.config)
        //         });
        // }

        // handleChange = (pagination, filters, sorter) => {
        //     //console.log('Various parameters', pagination, filters, sorter);
        //     this.setState({
        //         filteredInfo: filters,
        //         sortedInfo: sorter,
        //     });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchUserNumber: selectedKeys[0],
        //     searchName: selectedKeys[0],
        //     searchEmployer: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchUserNumber: '',
        //     searchName: '',
        //     searchEmployer: '',
        // });
    }

    render() {
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
            width: '10%',
        }, {
            title: "编号",
            dataIndex: "usernumber",
            key: "usernumber",
            width: '15%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.usernumber.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            width: '15%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: '部门',
            dataIndex: 'employer',
            key: 'employer',
            width: '25%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.employer.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: '照片',
            dataIndex: 'faceimage',
            key: 'faceimage',
            width: '10%',
            render: (text, record) => {
                return (<a href="javascript:;" onClick={() => this.checkImage(text)}>查看照片</a>)
            }
        }, {
            title: '录入情况',
            dataIndex: 'condition',
            key: 'condition',
            width: '15%',
            render: (text, record) => {
                let error = <Tag color="volcano">未录入</Tag>
                let correct = <Tag color="blue">已录入</Tag>
                return (
                    text > 0 ? error : correct
                )
            }
        }, {
            title: "操作",
            key: "action",
            width: '10%',
            render: (text, record) => {
                return (
                    <span>
                        <a href="javascript:;" onClick={() => this.handleUpdateFaceImage(record)}>更新</a>
                        <Divider type="vertical" />
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDeleteFaceImage(record.usernumber)}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }
        }]
        return (
            <div>
                <Modal
                    destroyOnClose
                    visible={this.state.imageVisible}
                    title={'人脸认证图'}
                    footer={null}
                    width={700}
                    style={{ textAlign: "center" }}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.imageModalCancel() }}>
                    <img style={{ width: 'auto', height: '100%' }} src={UrlPrefix + this.state.imageUrl} alt={'请检查网络或图片已失效'} />
                </Modal>
                <Table
                    dataSource={this.state.tableData}
                    columns={columns}
                    className="components-table-demo-nested"
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    expandedRowRender={(record) => {
                        return (
                            <DeviceEnterConditionTable
                                that={this}
                                FatherKey={record.key}
                                usernumber={record.usernumber}
                            />)
                    }}
                    pagination={{  //分页
                        total: this.state.tableData.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}

class DeviceEnterConditionTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            usernumber: props.usernumber,
            FatherKey: props.FatherKey,
            that: props.that,
            tableLoading: false,
            columnData: [],
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getDeviceEnterConditionByUserNumberApi(parseInt(sessionStorage.getItem("departmentId")), this.state.usernumber)
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index,
                        id: item.id,
                        deviceId: item.deviceId,
                        devicetype: item.devicetype,
                        name: item.name,
                        type: item.type,
                        enter: item.enter,
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    deleteUpdateRecord(id, key) {
        message.error('本地服务未上线，暂不支持');
        // this.setState({
        //     tableLoading: true
        // });
        // deleteUpdateRecordApi(id)
        //     .then((res) => {
        //         if (res.data == "success") {

        //             this.setState({
        //                 tableLoading: false,
        //             });
        //             this.refreshData();
        //             if (this.state.columnData[key].enter == 0) {
        //                 console.log(this.state.FatherKey)
        //                 this.state.that.forInnerTableChange(this.state.FatherKey);
        //             }
        //         } else {
        //             message.error('删除失败,请稍后再试!');
        //         }
        //     })
        //     .catch((e) => {
        //         if (e.response) {
        //             //请求已发出，服务器返回状态码不是2xx。
        //             console.info(e.response.data)
        //             console.info(e.response.status)
        //             console.info(e.response.headers)
        //         } else if (e.request) {
        //             // 请求已发出，但没有收到响应
        //             // e.request 在浏览器里是一个XMLHttpRequest实例，
        //             // 在node中是一个http.ClientRequest实例
        //             console.info(e.request)
        //         } else {
        //             //发送请求时异常，捕捉到错误
        //             console.info('error', e.message)
        //         }
        //         console.info(e.config)
        //     });
    }


    render() {
        const columns2 = [
            {
                title: "设备编号",
                dataIndex: "deviceId",
                key: "deviceId"
            },
            {
                title: "设备名称",
                dataIndex: "name",
                key: "name",
            },
            {
                title: "设备类型",
                dataIndex: "devicetype",
                key: "devicetype",
                render: (text, record) => {
                    let type = {
                        "facerecord": "人脸闸机",
                        "visit": "访客机",
                        "smoke": "烟感",
                        "upanddown": "升降柱",
                    }
                    return type[text];
                }
            },
            {
                title: "录入类型",
                key: "type",
                dataIndex: "type",
                render: (text, record) => {
                    let status = {
                        "update": "更新",
                        "add": "添加",
                        "delete": "删除",
                    }
                    console.log(text, status[text])
                    return (<Tag color="cyan">{status[text]}</Tag>)
                }
            },
            {
                title: "录入情况",
                dataIndex: "enter",
                key: "enter",
                render: (text, record) => {
                    let error = <Tag color="volcano">未录入</Tag>
                    let correct = <Tag color="blue">已录入</Tag>
                    return (
                        text == 0 ? error : correct
                    )
                }
            },
            {
                title: "操作",
                key: "action",
                render: (text, record) => {
                    return (
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.deleteUpdateRecord(record.id, record.key)}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    )
                }
            },
        ];
        return (
            <Table
                columns={columns2}
                dataSource={this.state.columnData}
                pagination={false}
                locale={{ emptyText: '暂无数据' }}
                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                bordered={true}
                loading={this.state.tableLoading}
                size='small'
            />)
    }
}




class VisitorNameToday extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
        };
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        let data = this.state.chartData;
        if (this.state.chartData.length > 4) {
            data = this.state.chartData.slice(0, 4);
        }
        return (
            <div id='VisitorNameToday' style={chartStyle}>
                <List
                    itemLayout="horizontal"
                    size='small'
                    dataSource={data}
                    renderItem={(item, index) => {
                        let backgroundColor;
                        let fontColor;
                        if (index < 3) {
                            backgroundColor = '#314659';
                            fontColor = '#fff';
                        } else {
                            backgroundColor = '#f5f5f5';
                            fontColor = 'rgba(0,0,0,.65)';
                        }

                        let firstPaddingTop;
                        if (index == 0) {
                            firstPaddingTop = 4;
                        } else {
                            firstPaddingTop = 8;
                        }
                        return (
                            <List.Item
                                style={{
                                    borderBottom: 0,
                                    paddingTop: firstPaddingTop,
                                }}>
                                <Avatar
                                    style={{
                                        backgroundColor: backgroundColor,
                                        verticalAlign: 'middle',
                                        color: fontColor,
                                        marginLeft: 12,
                                        marginTop: 1,
                                        fontSize: 12,
                                        lineHeight: '22px',
                                    }}
                                    size={20}>
                                    {index + 1}
                                </Avatar>
                                <span
                                    style={{
                                        marginLeft: 20,
                                        flex: '1 1',
                                        marginRight: 12,
                                        overflow: 'hidden',
                                        whiteSpace: 'nowrap',
                                        textOverflow: 'ellipsis',
                                        fontSize: 14,
                                        lineHeight: '22px',
                                        width: 100,
                                    }}>
                                    {item.visitorName}
                                </span>
                                <span
                                    style={{
                                        marginRight: 24,
                                        fontSize: 14,
                                        lineHeight: '22px',
                                    }}>
                                    {item.stayTime}
                                </span>
                            </List.Item>
                        )
                    }}
                />
            </div>
        )
    }
}

class ChartDataVisitorNumRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
        };
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        let data = this.state.chartData;
        if (this.state.chartData.length > 4) {
            data = this.state.chartData.slice(0, 4);
        }
        return (
            <div id='ChartDataVisitorNumRank' style={chartStyle}>
                <List
                    itemLayout="horizontal"
                    size='small'
                    dataSource={data}
                    renderItem={(item, index) => {
                        let backgroundColor;
                        let fontColor;
                        if (index < 3) {
                            backgroundColor = '#314659';
                            fontColor = '#fff';
                        } else {
                            backgroundColor = '#f5f5f5';
                            fontColor = 'rgba(0,0,0,.65)';
                        }

                        let firstPaddingTop;
                        if (index == 0) {
                            firstPaddingTop = 4;
                        } else {
                            firstPaddingTop = 8;
                        }
                        return (
                            <List.Item
                                style={{
                                    borderBottom: 0,
                                    paddingTop: firstPaddingTop,
                                }}>
                                <Avatar
                                    style={{
                                        backgroundColor: backgroundColor,
                                        verticalAlign: 'middle',
                                        color: fontColor,
                                        marginLeft: 12,
                                        marginTop: 1,
                                        fontSize: 12,
                                        lineHeight: '22px',
                                    }}
                                    size={20}>
                                    {index + 1}
                                </Avatar>
                                <span
                                    style={{
                                        marginLeft: 20,
                                        flex: '1 1',
                                        marginRight: 12,
                                        overflow: 'hidden',
                                        whiteSpace: 'nowrap',
                                        textOverflow: 'ellipsis',
                                        fontSize: 14,
                                        lineHeight: '22px',
                                        width: 100,
                                    }}>
                                    {item.dateRank}
                                </span>
                                <span
                                    style={{
                                        marginRight: 24,
                                        fontSize: 14,
                                        lineHeight: '22px',
                                    }}>
                                    {item.times}
                                </span>
                            </List.Item>
                        )
                    }}
                />
            </div>
        )
    }
}
class visitorrecord extends Component {
    constructor(props) {
        super(props);
        this.state = {
            //detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            // searchText: '',
            // allCategory: [],
            // allStatus: []
            isSearch: false,
            deviceIdArr: [],
            existCategory: [],
            searchData: [],
            filteredInfo2: null,
            sortedInfo2: null,
            // searchText2: '',

            detailVisible: false,
            detailExist: false,

            // searchChartLoading: true,
            // chartInspectSearchData: {}
        };

    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let deviceIdArr = [];
        //let statusData = [];
        getVisitorMessageApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    columnData.push({
                        key: index + 1,
                        deviceId: item.deviceId,
                        address: item.address,
                        visitorname: item.visitor_name,
                        visitorIdcard: item.visitor_Idcard,
                        visitedid: item.visited_id,
                        datetime: item.date_time,
                        content: item.content,
                        leavetime: item.leave_time,
                        visitorPic: item.visitorPic
                    });
                    if (deviceIdArr.indexOf(item.deviceId) == -1) {
                        deviceIdArr.push(item.deviceId);
                    }

                    //statusData.push(item.statusString);
                });
                this.setState({
                    columnData: columnData,
                    deviceIdArr: deviceIdArr,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        // let existCategory=[];
        // getExistCategoryBySchoolIdAip(parseInt(sessionStorage.getItem("departmentId")))
        //     .then((res) => {
        //         // res.data.forEach((item, index) => {
        //         //     //console.log("getAllUser", item);
        //         //     existCategory.push({
        //         //         categoryId: item.categoryId,
        //         //         categoryName: item.categoryName,
        //         //     });
        //         //     //statusData.push(item.statusString);
        //         // });
        //         this.setState({
        //             existCategory: res.data,
        //         });
        //     })
        //     .catch((e) => {
        //         if (e.response) {
        //             //请求已发出，服务器返回状态码不是2xx。
        //             console.info(e.response.data)
        //             console.info(e.response.status)
        //             console.info(e.response.headers)
        //         } else if (e.request) {
        //             // 请求已发出，但没有收到响应
        //             // e.request 在浏览器里是一个XMLHttpRequest实例，
        //             // 在node中是一个http.ClientRequest实例
        //             console.info(e.request)
        //         } else {
        //             //发送请求时异常，捕捉到错误
        //             console.info('error', e.message)
        //         }
        //         console.info(e.config)
        //     });
    }

    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            // console.log('Received values of form: ', values);
            // console.log('-------------------------------------------------------------------');
            // console.log(values.deadline[0]);
            // console.log(values.deadline[1]);
            if (values.deviceId == undefined && values.visitorname == undefined && values.deadline == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true
                });
                let searchData = [];
                getVisitorrecordSearchApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then(res => {
                        res.data.forEach((item, index) => {
                            searchData.push({
                                key: index + 1,
                                deviceId: item.deviceId,
                                address: item.address,
                                visitorname: item.visitorname,
                                visitorIdcard: item.visitorIdcard,
                                content: item.content,
                                datetime: item.datetime,
                                leavetime: item.leavetime
                            });
                            //statusData.push(item.statusString);
                        });
                        this.setState({
                            isSearch: true,
                            searchData: searchData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

                // getInspectSearchChartDataApi(parseInt(sessionStorage.getItem("departmentId")), values)
                //     .then(res => {
                //         let chartInspectSearchData = {
                //             date: [],
                //             doneNumber: [],
                //         };
                //         res.data.forEach((item, index) => {
                //             chartInspectSearchData.date.push(item.date);
                //             chartInspectSearchData.doneNumber.push(item.doneNumber);
                //         });

                //         this.setState({
                //             searchChartLoading: false,
                //             chartInspectSearchData: chartInspectSearchData,
                //             alertVisible: false,
                //         });
                //     })
                //     .catch((e) => {
                //         if (e.response) {
                //             //请求已发出，服务器返回状态码不是2xx。
                //             console.info(e.response.data)
                //             console.info(e.response.status)
                //             console.info(e.response.headers)
                //         } else if (e.request) {
                //             // 请求已发出，但没有收到响应
                //             // e.request 在浏览器里是一个XMLHttpRequest实例，
                //             // 在node中是一个http.ClientRequest实例
                //             console.info(e.request)
                //         } else {
                //             //发送请求时异常，捕捉到错误
                //             console.info('error', e.message)
                //         }
                //         console.info(e.config)
                //     });
            }
        });
    }
    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    clearAll2 = () => {
        this.setState({
            filteredInfo2: null,
            sortedInfo2: null,
        });

    }

    handleChange2 = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo2: filters,
            sortedInfo2: sorter,
        });
    }

    handleSearch2 = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     // searchText2: selectedKeys[0],
        // });
    }

    handleSearchReset2 = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     // searchText2: '',
        // });
    }

    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
        })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }




    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        },
        {
            title: "设备编号",
            dataIndex: "deviceId",
            key: "deviceId",
        },
        {
            title: "设备位置",
            dataIndex: "address",
            key: "address",
        },
        {
            title: "访客姓名",
            dataIndex: "visitorname",
            key: "visitorname",
        },
        {
            title: "访客卡号",
            dataIndex: "visitorIdcard",
            key: "visitorIdcard",
        },
        {
            title: "访问内容",
            dataIndex: "content",
            key: "content",
        },
        {
            title: "访问时间",
            dataIndex: "datetime",
            key: "datetime",
        },
        {
            title: "离开时间",
            dataIndex: "leavetime",
            key: "leavetime",
        }];

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo2, filteredInfo2 } = this.state;
        sortedInfo2 = sortedInfo2 || {};
        filteredInfo2 = filteredInfo2 || {};


        let keyWidth = undefined;
        let classmatesWidth = undefined;
        let deadlineWidth = undefined;
        let categoryNameWidth = undefined;
        let doneStatusWidth = undefined;
        let actionWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            classmatesWidth = 90;
            deadlineWidth = 120;
            categoryNameWidth = 110;
            doneStatusWidth = 110;
            actionWidth = 110;
        }

        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        },
        {
            title: "设备编号",
            dataIndex: "deviceId",
            key: "deviceId",
        },
        {
            title: "设备位置",
            dataIndex: "address",
            key: "address",
        },
        {
            title: "访客姓名",
            dataIndex: "visitorname",
            key: "visitorname",
        },
        {
            title: "访客卡号",
            dataIndex: "visitorIdcard",
            key: "visitorIdcard",
        },
        {
            title: "访问内容",
            dataIndex: "content",
            key: "content",
        },
        {
            title: "访问时间",
            dataIndex: "datetime",
            key: "datetime",
        },
        {
            title: "离开时间",
            dataIndex: "leavetime",
            key: "leavetime",
        }];

        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="设备编号"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deviceId", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.deviceIdArr}
                                        placeholder="请输入设备编号"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="访客时间段"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="访客姓名"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("visitorname", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入访客姓名"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                    </Row>

                    <Row>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                {this.state.isSearch ? (
                    <div>
                        {/* <div style={{
                            marginBottom: 16,
                            padding: 16,
                            width: '100%',
                            height: 300,
                            border: '1px solid',
                            borderColor: '#f5f5f5'
                        }}>
                            <Skeleton loading={this.state.searchChartLoading} active>
                                <ChartInspectSearch
                                    that={this}
                                    chartData={this.state.chartInspectSearchData} />
                            </Skeleton>
                        </div>
                         */}
                        <Table
                            dataSource={this.state.searchData}
                            columns={columnsSearch}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            onChange={this.handleChange2}
                            rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                            pagination={{  //分页
                                total: this.state.searchData.length, //数据总数量
                                defaultPageSize: 10, //默认显示几条一页
                                //pageSize: 10,
                                showTotal: function (total) {  //设置显示一共几条数据
                                    return '共 ' + total + ' 条数据';
                                },
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSizeOptions: [5, 10, 20, 30]
                            }} />
                    </div>
                ) : (
                    <Table
                        dataSource={this.state.columnData}
                        columns={columns}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.data.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                )}
                {
                    this.state.detailExist ? (
                        <InspectConditionDetail
                            visible={this.state.detailVisible}
                            currentInspectPlanIds={this.state.currentInspectPlanIds}
                            currentItems={this.state.currentItems}
                            currentStatusArr={this.state.currentStatusArr}
                            currentSinglePlanNormalArr={this.state.currentSinglePlanNormalArr}
                            that={this} />
                    ) : null
                }
            </div>
        )
    }
}
const Visitorrecord = Form.create()(visitorrecord);

class VisitorrecordData extends Component {
    constructor(props) {
        super(props);

        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            chartsNum: 5,
            doneChartsNum: 0,
            // chartDataPatrolDay: {},
            chartDataVisitorDay: {
                date: [],
                times: []
            },
            chartDataVisitorNumRank: [],
            chartDataVisitorNameToday: [],
            // chartDataPatrolAll: {},
            topChartDataToday: {
                should: 0,
                real: 0,
                safetySceneFound: 0,
                safetySceneDeal: 0,
                inspectReal: 0
            },
            topChartDataAll: {
                inspectReal: 0,
                patrolReal: 0,
                safetySceneFound: 0,
                safetySceneDeal: 0
            },
            modalTitle: '',
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            confirmLoading: true,
            doneChartsNum: 0,
        });

        getVisitorTimeByDay(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let chartData = {
                    date: [],
                    times: [],
                };
                res.data.forEach((item, index) => {
                    chartData.date.push(item.ymdDate);
                    chartData.times.push(item.times);
                });

                this.setState({
                    chartDataVisitorDay: chartData,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getVisitorNumRank(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    chartDataVisitorNumRank: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getVisitorNameToday(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    chartDataVisitorNameToday: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getTodayVisitorInfo(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    topChartDataToday: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getAllTimeInfo(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    topChartDataAll: res.data,
                    doneChartsNum: this.state.doneChartsNum + 1,
                });

                //所有图表数据都加载完成才使骨架屏可见
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    setFullScreen(title, opts) {
        this.setState({
            fullScreenVisible: true,
            modalTitle: title
        })
        this.setState({
            fullVisible: true,
        });
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    handleCancel() {
        this.setState({
            fullScreenVisible: false,
            calendarVisible: false,
            fullVisible: false,
        })
    }

    render() {
        let gridStyle = {
            marginBottom: 24,
        };

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            //
        }
        // console.log('JSON.stringify(this.state.chartDataInspectDay)', JSON.stringify(this.state.chartDataInspectDay))
        return (
            <div style={{ background: '#f0f2f5', margin: -24, }}>
                <Row gutter={24}>
                    <Col span={6}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(233, 217, 211)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/visitorToday.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            <div dangerouslySetInnerHTML={{ __html: '今日访客数' }} />
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.visitorNumToday}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                    <Col span={6}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(210, 208, 223)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/visitorThisWeek.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            <div dangerouslySetInnerHTML={{ __html: '本周访客数' }} />
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.visitorNumWeek}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                    <Col span={6}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(207, 218, 213)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/visitorCount.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            <div dangerouslySetInnerHTML={{ __html: '累计访客数' }} />
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.visitorNum}
                                            {/* {this.state.topChartDataToday.visitorNum} */}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                    <Col span={6}>
                        <Card
                            style={gridStyle}
                            bodyStyle={{
                                height: 160,
                                padding: '12px 16px',
                                backgroundColor: 'rgb(210, 208, 223)',
                            }}
                            bordered={false}>
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Row
                                    style={{ height: '100%' }}
                                    type="flex"
                                    justify="space-around"
                                    align="middle">
                                    <Col span={6}>
                                        <img className="charticon"
                                            src={require("../img/visitorDeviceCount.png")} />
                                    </Col>
                                    <Col span={18} style={{ width: 200 }}>
                                        <Row style={{
                                            fontSize: "20px",
                                            fontWeight: "bold",
                                            color: "#000",
                                            textAlign: "center",
                                        }}>
                                            <div dangerouslySetInnerHTML={{ __html: '访客设备数' }} />
                                        </Row>
                                        <Row style={{
                                            fontSize: "30px",
                                            fontWeight: "bold",
                                            textAlign: "center",
                                        }}>
                                            {this.state.topChartDataToday.deviceNum}
                                        </Row>
                                    </Col>
                                </Row>
                            </Skeleton>
                        </Card>
                    </Col>
                </Row>
                <Row gutter={24}>
                    <Col span={16}>
                        <Row>
                            <Card
                                title={'每日访客次数统计'}
                                style={gridStyle}
                                bodyStyle={{ height: 440, padding: 24 }}
                                bordered={false}>
                                <Skeleton loading={this.state.confirmLoading} active>
                                    {
                                        (JSON.stringify(this.state.chartDataVisitorDay) == '{"date":[],"times":[]}') ?
                                            (
                                                <Empty
                                                    style={{
                                                        marginTop: 100,
                                                    }} />
                                            ) :
                                            (
                                                <ChartDataVisitorDay
                                                    chartData={this.state.chartDataVisitorDay}
                                                    that={this} />
                                            )
                                    }
                                </Skeleton>
                            </Card>
                        </Row>
                    </Col>
                    <Col span={8}>
                        <Row>

                            <Card
                                title={'今日访客'}
                                style={gridStyle}
                                bodyStyle={{ height: 180, padding: 12 }}
                                bordered={false}>

                                <Skeleton loading={this.state.confirmLoading} active>
                                    <VisitorNameToday
                                        chartData={this.state.chartDataVisitorNameToday} />
                                </Skeleton>
                            </Card>
                        </Row>
                        <Row>
                            <Card
                                title={'本周访客数排名'}
                                style={gridStyle}
                                bodyStyle={{ height: 180, padding: 12 }}
                                bordered={false}>
                                <Skeleton loading={this.state.confirmLoading} active>
                                    <ChartDataVisitorNumRank chartData={this.state.chartDataVisitorNumRank} />
                                </Skeleton>
                            </Card>
                        </Row>
                    </Col>
                </Row>
                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={this.state.modalTitle}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.handleCancel() }}>
                    {this.state.fullVisible ?
                        (
                            <div id='fullScreen'
                                style={{
                                    width: '100%',
                                    height: '100%',
                                }} />
                        ) : undefined
                    }
                </Modal>
            </div>
        )
    }
}

class Score extends Component {
    constructor(props) {
        super(props);

        this.state = {
            tableLoading: true,
            outerData: [],
        };

    }

    componentDidMount() {
        this.refreshData();
    }


    refreshData() {
        this.setState({
            tableLoading: true
        });
        let outerColumnData = [];
        getAllScoreDate(sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    outerColumnData.push({
                        key: index + 1,
                        startDate: item.startDate,
                        endDate: item.endDate
                    });
                });
                this.setState({
                    outerData: outerColumnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    onRef = (ref) => {
        this.child = ref
    }


    render() {
        const outerColumns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "开始日期",
            dataIndex: "startDate",
            key: "startDate"
        }, {
            title: "结束日期",
            dataIndex: "endDate",
            key: "endDate"
        }];

        // console.log(this.state.outerData);

        return (
            <div>
                <Table
                    dataSource={this.state.outerData}
                    columns={outerColumns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    expandedRowRender={(record) => {
                        return (
                            <ScoreDetails
                                onRef={this.onRef}
                                startDate={record.startDate}
                                endDate={record.endDate}
                                that={this} />)
                    }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.outerData.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </div>
        )
    }
}

class ScoreDetails extends Component {
    constructor(props) {
        super(props);
        const innerColumns = [{
            title: '真实姓名',
            dataIndex: 'realName',
            key: 'realName',
            width: '20%',
            render: (text, record, index) => {
                const obj = {
                    children: text,
                    props: {},
                };
                if (index % record.row === 0) obj.props.rowSpan = record.row;
                else obj.props.rowSpan = 0;
                return obj;
            }
        }, {
            title: '积分项目',
            dataIndex: 'detailname',
            key: 'detailname',
            width: '20%',
            render: (text, record, index) => {
                const obj = {
                    children: text,
                    props: {
                        rowSpan: 1
                    },
                };
                return obj;
            }
        }, {
            title: '积分',
            dataIndex: 'score',
            key: 'score',
            width: '20%',
            render: (text, record, index) => {
                const obj = {
                    children: text,
                    props: {},
                };
                return obj;
            }
        }, {
            title: '总积分',
            dataIndex: 'total',
            key: 'total',
            width: '20%',
            render: (text, record, index) => {
                const obj = {
                    children: text,
                    props: {},
                };
                if (index % record.row === 0) obj.props.rowSpan = record.row;
                else obj.props.rowSpan = 0;
                return obj;
            }
        }];

        this.state = {
            tableLoading: true,
            startDate: props.startDate,
            endDate: props.endDate,
            innerColumns: innerColumns,
            that: props.that
        }
    }

    componentDidMount() {
        this.refreshData();
        this.props.onRef(this);
    }

    componentWillReceiveProps(props) {
        this.setState({
            startDate: props.startDate,
            endDate: props.endDate,
            that: props.that,
        });
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        getScoreDetailByDate(sessionStorage.getItem("departmentId"), this.state.startDate, this.state.endDate)
            .then((res) => {
                let index = 1;
                res.data.forEach((item, index) => {
                    item.detail.forEach((detail) => {
                        innerData.push({
                            key: index++,
                            realName: item.realName,
                            detailname: detail.name,
                            score: detail.score,
                            total: item.total,
                            row: item.detail.length
                        });
                    })
                });
                this.setState({
                    innerData: innerData,
                    tableLoading: false
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    render() {
        return (
            <Table
                columns={this.state.innerColumns}
                dataSource={this.state.innerData}
                pagination={false}
                size='small'
                loading={this.state.tableLoading}
                locale={{ emptyText: '暂无数据' }}
                bordered={true}
                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
            />
        )
    }
}
const SchoolPatrolConditionManager = Form.create()(schoolPatrolConditionManager);

export default SchoolSafetySupervisor;
export {
    SchoolTeamAssignmentManager, PatrolRouteManager, SchoolPatrolPlanManager, SchoolPatrolConditionManager,
    SchoolInspectWithCheckpointManager, SchoolInspectPlanManager, SchoolInspectConditionManager, SchoolSafetySceneManager,
    PatrolCharts, InspectCharts, MonitorTable, Electricalsafety, ElectricalsafetyDeploy,
    SmokeDevice, UpAndDownDevice, FaceImageManage, Visitorrecord, VisitorrecordData, Score
}